Kubernetes -- endpoints资源类型

endpoints是一种kubernetes资源类型,它是namespace scoped,简写为ep:

kubectl api-resources|grep endpoints
endpoints                         ep                                          true         Endpoints

endpoints有两种使用方法:

  • 随service被创建:

    • 创建service对象的同时,kubernetes会创建同名的endpoints的对象;
    • service的podSelector会将目标pod的endpoint信息(ip/port),添加到endpoints对象中;
  • 独立创建endpoints:

    • enpdoints作为一种资源类型,支持用户创建;
    • 将外部服务的endpoint添加到endpoints对象,可以使用kubernetes service访问外部服务;

service与endpoints

以一个简单的例子,来演示endpoints随service被自动创建出来。
创建nginx deploy,含2个pod:

apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: nginx
  name: nginx
spec:
  replicas: 2
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:latest
        imagePullPolicy: IfNotPresent
        command:
        - nginx
        - -g
        - "daemon off;"
        workingDir: /usr/share/nginx/html
        ports:
        - name: http
          containerPort: 80
          protocol: TCP

创建nginx service:

apiVersion: v1
kind: Service
metadata:
  name: nginx-svc
spec:
  ports:
  - port: 80
    targetPort: 80
  selector:
    app: nginx

查看其service和endpoints资源:有一个同名的endpoints被创建出来

# kubectl get svc,endpoints
NAME                 TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)   AGE
service/nginx-svc    ClusterIP   10.233.26.39           80/TCP    3m2s

NAME                   ENDPOINTS                                                       AGE
endpoints/nginx-svc    10.233.96.113:80,10.233.97.95:80                3m2s

其endpoints的内容,实际是nginx pod的ip+port:

# kubectl get pod -owide
NAME                    READY   STATUS    RESTARTS   AGE    IP              NODE      NOMINATED NODE   READINESS GATES
nginx-6dcdfd5b8-8q7l5   1/1     Running   0          4m3s   10.233.97.95    master1              
nginx-6dcdfd5b8-xsl96   1/1     Running   0          4m3s   10.233.96.113   master3              

外部服务与endpoints

手动创建endpoints,添加外部服务的endpoint,可以将外部服务作为kubernetes的service使用。
etcd有3节点部署在外部,为其创建service: etcd-k8s,不指定podSelector:

apiVersion: v1
kind: Service
metadata:
  name: etcd-k8s
  namespace: kube-system
spec:
  type: ClusterIP
  ports:
  - name: port
    port: 2379
    protocol: TCP

创建同名的endpoints资源: etcd-k8s,将etcd节点的ip+port填进去:

apiVersion: v1
kind: Endpoints
metadata:
  name: etcd-k8s
  namespace: kube-system
subsets:
- addresses:
  - ip: 178.104.163.38
    nodeName: etc-master1
  - ip: 178.104.163.187
    nodeName: etc-master2
  - ip: 178.104.163.243
    nodeName: etc-master3
  ports:
  - name: port
    port: 2379
    protocol: TCP

这样,通过serviceName.namespace:port就可以在kubernetes集群内访问外部的etcd服务:

etcd-k8s.kube-system:2379

你可能感兴趣的:(kubernetes)