Service控制器

由于Pod重建之后ip就变了,因此pod之间使用的IP直接访问会出现无法访问的问题,而service则解耦了服务和应用,service的实现方式就是通过label标签动态匹配后端endpoint。

kube-proxy 监听着k8s-apiserver,一旦service资源发生变化(调k8s-api修改service信息),kube-proxy 就会生成对应得负载调度得调整,这样就保证了service得最新状态

service

service类型:

  • ClusterIP:用于内部服务基于service name的访问
  • NodePort:用于K8s集群以外的服务主动访问运行在kubernetes集群内部的服务
  • LoadBalancer:用于公有云环境的服务暴露
  • ExternalName:用于将k8s集群外部的服务映射至K8s集群内部访问,从而让集群内部的pod能够通过固定的service name访问集群外部的服务,有时候也用于将不同namespace 之间的pod通过ExternalName 进行访问

clusterIP:

[root@haproxy1 case4-service]# cat 1-deploy_node.yml 
#apiVersion: extensions/v1beta1
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
spec:
  replicas: 1
  selector:
    #matchLabels: #rs or deployment
    #  app: ng-deploy3-80
    matchExpressions:
      - {key: app, operator: In, values: [ng-deploy-80,ng-rs-81]}
  template:
    metadata:
      labels:
        app: ng-deploy-80
    spec:
      containers:
      - name: ng-deploy-80
        image: nginx:1.17.5 
        ports:
        - containerPort: 80
      #nodeSelector:
      #  env: group1
#在其他的pod
[root@haproxy1 case4-service]# cat 2-svc_service.yml 
apiVersion: v1
kind: Service
metadata:
  name: ng-deploy-80 
spec:
  ports:
  - name: http
    port: 80
    targetPort: 80
    protocol: TCP
  type: ClusterIP
#这里的selector 对应deployment 的template  metadata下的labels通过这个标签选择器找到指定的deployment控制器
  selector:
    app: ng-deploy-80
[root@haproxy1 case4-service]# kubectl get svc 
NAME           TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)   AGE
kubernetes     ClusterIP   10.100.0.1      <none>        443/TCP   15d
ng-deploy-80   ClusterIP   10.100.41.139   <none>        80/TCP    11m
[root@haproxy1 case4-service]# 
#查看svc对应的后端pod
[root@haproxy1 case4-service]# kubectl get ep
NAME           ENDPOINTS                               AGE
kubernetes     172.16.92.130:6443,172.16.92.131:6443   15d
ng-deploy-80   10.200.107.219:80                       3d2h
[root@haproxy1 case4-service]# 

Nodeport:

[root@haproxy1 case4-service]# cat 3-svc_NodePort.yml 
apiVersion: v1
kind: Service
metadata:
  name: ng-deploy-80 
spec:
  ports:
  - name: http
    port: 81
    targetPort: 80
    nodePort: 30012
    protocol: TCP
  type: NodePort
  selector:
    app: ng-deploy-80
#此时就可以直接访问podip+30012 端口访问了
#如果前端有负载均衡可以添加到负载均衡里,如haproxy:
listen dujie-nginx-80
    bind 172.16.92.189:80
    mode tcp
    server k8s-node1 172.16.92.140:30012 check inter 3s fall 3 rise 1
    server k8s-node2 172.16.92.141:30012 check inter 3s fall 3 rise 1
    server k8s-node3 172.16.92.142:30012 check inter 3s fall 3 rise 1