Headless Services
Services allow internal and external pod access, but not the following scenarios:
- Accessing all pods at the same time
- Pods in a Service accessing each other
This is where headless Service come into service. A headless Service does not create a cluster IP address, and the DNS records of all pods are returned during query. In this way, the IP addresses of all pods can be queried. StatefulSets use headless Services to support mutual access between pods.
apiVersion: v1kind: Service # Object type (Service)metadata:name: nginx-headlesslabels:app: nginxspec:ports:- name: nginx # - name: nginx # Name of the port for communication between podsport: 80 # Port number for communication between podsselector:app: nginx # Select the pod whose label is app:nginx.clusterIP: None # Set this parameter to None, indicating that a headless Service is to be created.
Run the following command to create a headless Service:
# kubectl create -f headless.yamlservice/nginx-headless created
After the Service is created, you can query the Service.
# kubectl get svcNAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGEnginx-headless ClusterIP None <none> 80/TCP 5s
Create a pod to query the DNS. You can view the records of all pods. In this way, all pods can be accessed.
$ kubectl run -i --tty --image tutum/dnsutils dnsutils --restart=Never --rm /bin/shIf you do not see a command prompt, try pressing Enter./ # nslookup nginx-0.nginxServer: 10.247.3.10Address: 10.247.3.10#53Name: nginx-0.nginx.default.svc.cluster.localAddress: 172.16.0.31/ # nslookup nginx-1.nginxServer: 10.247.3.10Address: 10.247.3.10#53Name: nginx-1.nginx.default.svc.cluster.localAddress: 172.16.0.18/ # nslookup nginx-2.nginxServer: 10.247.3.10Address: 10.247.3.10#53Name: nginx-2.nginx.default.svc.cluster.localAddress: 172.16.0.19
Parent topic: Service