0
0
Kubernetesdevops~5 mins

Headless services concept in Kubernetes - Commands & Configuration

Choose your learning style9 modes available
Introduction
Sometimes you want to connect directly to individual pods in Kubernetes instead of through a load balancer. Headless services let you do this by removing the usual IP address and load balancing, so you get the real pod addresses.
When you want to discover and connect to each pod directly for custom routing or stateful apps.
When you run databases or caches that need to talk to specific pods instead of any pod.
When you want to manage your own load balancing outside Kubernetes.
When you need to use StatefulSets that require stable network IDs for each pod.
When you want to expose pods without a cluster IP to reduce network overhead.
Config File - headless-service.yaml
headless-service.yaml
apiVersion: v1
kind: Service
metadata:
  name: my-headless-service
  namespace: default
spec:
  clusterIP: None
  selector:
    app: my-app
  ports:
  - protocol: TCP
    port: 80
    targetPort: 8080

This YAML defines a headless service named my-headless-service in the default namespace.

The key part is clusterIP: None, which disables the usual cluster IP and load balancing.

The selector matches pods with label app: my-app, so this service tracks those pods.

The ports section exposes port 80 on the service, forwarding to port 8080 on the pods.

Commands
This command creates the headless service in Kubernetes using the YAML file. It sets up the service without a cluster IP.
Terminal
kubectl apply -f headless-service.yaml
Expected OutputExpected
service/my-headless-service created
This command checks the service details to confirm it is headless by showing clusterIP as None.
Terminal
kubectl get svc my-headless-service
Expected OutputExpected
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE my-headless-service ClusterIP None <none> 80/TCP 10s
This command shows the actual pod IP addresses that the headless service points to, allowing direct pod access.
Terminal
kubectl get endpoints my-headless-service
Expected OutputExpected
NAME ENDPOINTS AGE my-headless-service 10.244.1.5:8080,10.244.1.6:8080 15s
Key Concept

If you remember nothing else from this pattern, remember: setting clusterIP to None creates a headless service that exposes pod IPs directly without load balancing.

Common Mistakes
Not setting clusterIP to None in the service spec.
The service will get a normal cluster IP and load balance traffic, not exposing individual pod IPs.
Always include 'clusterIP: None' in the service spec to make it headless.
Using a selector that does not match any pods.
The service will have no endpoints, so no pod IPs will be exposed.
Ensure the selector labels exactly match the pods you want to expose.
Summary
Create a service YAML with 'clusterIP: None' to make it headless.
Apply the YAML to create the headless service in Kubernetes.
Use 'kubectl get endpoints' to see the pod IPs exposed by the headless service.