Myluzh Blog

Strive to become a dream architect.

Kubernetes(k8s)-Service

发布时间: 2023-6-16 文章作者: myluzh 分类名称: Kubernetes


0x01 特性
Service 通过 label 关联对应的 Pod
Servcie 生命周期不跟 Pod 绑定,不会因为 Pod 重创改变 IP
提供了负载均衡功能,自动转发流量到不同 Pod
可对集群外部提供访问端口
集群内部可通过服务名字访问
service.png

0x02 创建Service(默认为ClusterIP类型
创建一个 Service,通过标签hellohttp跟对应的Pod关联上
service.yaml
apiVersion: v1
kind: Service
metadata:
 name: hellohttp
spec:
 selector:
   app: hellohttp   #这里一定要跟pod的标签对应上要不然关联不起来
 type: ClusterIP
 ports:
   - port: 8080        # 本 Service 的端口
     targetPort: 8080  # 容器端口
服务的默认类型是ClusterIP,只能在集群内部访问,我们可以进入到 Pod 里面访问:
kubectl exec -it pod-name -- bash
curl http://hellohttp:8080

如果要在集群外部访问,可以通过端口转发实现(只适合临时测试用):
kubectl port-forward service/hellohttp 8080:8080

应用配置 kubectl apply -f service.yaml
查看服务 kubectl get service
查看服务详情 kubectl describe service hellohttp (可以发现 Endpoints 是各个 Pod 的 IP,也就是他会把流量转发到这些节点)

0x03  NodePort类型(对外暴露服务
上面我们是通过端口转发的方式可以在外面访问到集群里的服务,如果想要直接把集群服务暴露出来,我们可以使用NodePort 和 Loadbalancer 类型的 Service
apiVersion: v1
kind: Service
metadata:
 name: hellohttp
spec:
 selector:
   app: hellohttp
 # 默认 ClusterIP 集群内可访问,NodePort 节点可访问,LoadBalancer 负载均衡模式(需要负载均衡器才可用)
 type: NodePort
 ports:
   - port: 8080        # 本 Service 的端口
     targetPort: 8080  # 容器端口
     nodePort: 31000   # 节点端口,范围固定只能是30000~32767(所谓节点就是宿主机服务器)
可以看到 NodePort模式,PORT后面会多出来一个端口,这个31000端口就是对外暴露的端口。
[root@master hellohttp]# kubectl get service
NAME         TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)          AGE
hellohttp    NodePort    10.106.249.197   <none>        8080:31000/TCP   31m

0x04 Loadbalancer模式
Loadbalancer 也可以对外提供服务,这需要一个负载均衡器的支持,因为它需要生成一个新的 IP 对外服务,否则状态就一直是 pendding,这个很少用了,后面我们会讲更高端的 Ingress 来代替它。

0x05 多端口写法
apiVersion: v1
kind: Service
metadata:
  name: hellohttp
spec:
  selector:
    app:  hellohttp
  type: NodePort
  ports:
    - port: 8080        # 本 Service 的端口
      name: hellohttp    # 必须配置
      targetPort: 8080  # 容器端口
      nodePort: 31000   # 节点端口,范围固定 30000 ~ 32767
    - port: 8090
      name: hellohttp-other
      targetPort: 8090
      nodePort: 32000
0x06 总结
ClusterIP
默认的,仅在集群内可用

NodePort
暴露端口到节点,提供了集群外部访问的入口,端口范围固定 30000 ~ 32767。

LoadBalancer
需要负载均衡器(通常都需要云服务商提供,裸机可以安装 metallb测试),会额外生成一个 IP 对外服务,K8S 支持的负载均衡器:负载均衡器

Headless
适合数据库 clusterIp 设置为 None 就变成 Headless 了,不会再分配 IP。

标签: k8s service k8s-service kubernetes

发表评论