Junior
What is the difference between a headless service and other types of services?
sobes.tech AI
Answer from AI
A headless service does not have a cluster IP address and does not perform load balancing. Instead, DNS directly returns the IP addresses of all pods matching the service selector. This allows the client to choose which pod to connect to or to use its own load balancing algorithm.
Typical use cases:
- StatefulSets: For applications requiring unique network identification and stable data storage.
- Discovery: Clients can directly discover pods and manage connections.
- Custom load balancing: Applications can implement their own load balancing algorithms.
Comparison with ClusterIP and NodePort services:
| Service Type | Cluster IP | Load Balancing | DNS |
|---|---|---|---|
| ClusterIP | Yes | Kubernetes | Returns service IP |
| NodePort | Yes | Kubernetes | Returns service IP |
| Headless | No | No (client) | Returns pod IP addresses |
Definition of a headless service in YAML:
apiVersion: v1
kind: Service
metadata:
name: my-headless-service
spec:
selector:
app: my-app # Selector for pods
clusterIP: None # Key difference - no cluster IP
ports:
- protocol: TCP
port: 80
targetPort: 8080
Instead of accessing my-headless-service via a single IP, the client will receive a list of pod IP addresses:
$ kubectl get pods -l app=my-app -o custom-columns=NAME:.metadata.name,IP:.status.podIP
NAME IP
my-app-abcde 10.42.0.10
my-app-fghij 10.42.0.11
my-app-klmno 10.42.0.12
The client can then choose any of these IP addresses to establish a connection.