Headless Services are a special type of Kubernetes Service. They do not provide a cluster IP address or load balancing through a Service IP address. Instead, when a client uses the DNS name of a headless Service for query, Kubernetes directly returns the individual IP addresses of the pods selected by the Service. This design allows clients to connect directly to the pods themselves. Headless Services are ideal for certain applications such as database clusters and cache clusters.
Headless Services are typically used in:
vi headless.yaml
File content:
apiVersion: v1kind: Service # Set the resource object type to Service.metadata:name: nginx-headlesslabels:app: nginxspec:ports:- name: web # Name of the port for communications between podsport: 80 # Port number for communications between podsselector:app: nginx # Select the pod labeled with app:nginx.clusterIP: None # Set this parameter to None, indicating that a headless Service will be created.---apiVersion: apps/v1kind: StatefulSetmetadata:name: webspec:serviceName: nginx-headless # Name of the headless Service associated with the StatefulSetreplicas: 3selector:matchLabels:app: nginxtemplate:metadata:labels:app: nginxspec:containers:- name: nginximage: nginx:alpineports:- containerPort: 80name: webimagePullSecrets:- name: default-secret
kubectl create -f headless.yaml
kubectl get pods -l app=nginx -o wide
Information similar to the following is displayed:
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATESweb-0 1/1 Running 0 41s 10.0.0.22 192.168.0.194 <none> <none>web-1 1/1 Running 0 38s 10.0.0.23 192.168.0.194 <none> <none>web-2 1/1 Running 0 37s 10.0.0.39 192.168.0.21 <none> <none>
kubectl get svc nginx-headless
Information similar to the following is displayed:
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGEnginx-headless ClusterIP None <none> 80/TCP 2m20s
kubectl run -it --rm --image=busybox:1.28 test-pod -- sh
The command for obtaining DNS is as follows:
nslookup nginx-headless
Information similar to the following is displayed:
Server: 10.247.3.10Address 1: 10.247.3.10 coredns.kube-system.svc.cluster.localName: nginx-headlessAddress 1: 10.0.0.22 web-0.nginx-headless.default.svc.cluster.localAddress 2: 10.0.0.23 web-1.nginx-headless.default.svc.cluster.localAddress 3: 10.0.0.39 web-2.nginx-headless.default.svc.cluster.local
This indicates that each StatefulSet pod has an independent DNS record.
wget -qO- web-0.nginx-headless