Kubernetes Headless Services

Featured image



Overview

Kubernetes Headless Services provide direct pod access without load balancing or cluster IP assignment, making them ideal for stateful applications and databases.


Key Features


No Cluster IP

DNS Records for Pods

Direct Pod Communication

Common Use Cases



Benefits of Headless Service

Segmented pas Access

Simplified DNS management

Stateful application support


How Headless Service Works

When you create Headless Service, Kubernetes generates DNS records differently.

my-service.default.svc.cluster.local -> No IP (headless service)
pod-0.my-service.default.svc.cluster.local -> Pod-0 IP
pod-1.my-service.default.svc.cluster.local -> Pod-1 IP
pod-2.my-service.default.svc.cluster.local -> Pod-2 IP


Create Headless Service

An example of a YAML configuration for Headless Service is as follows.

apiVersion: v1
kind: Service
metadata:
  name: headless-service
spec:
  clusterIP: None  # This makes it headless
  selector:
    app: my-app
  ports:
  - protocol: TCP
    port: 80
    targetPort: 8080

Integration with StatefulSet

StatefulSet often manages the pas network ID using the Headless Service. Each pas has a unique network ID and can be individually addressed.

web-0.headless-service.default.svc.cluster.local
web-1.headless-service.default.svc.cluster.local
web-2.headless-service.default.svc.cluster.local



Headless Service DNS Query Behavior

A/AAAA DNS query (default)

nslookup my-service.default.svc.cluster.local
Name: my-service.default.svc.cluster.local
Address: 10.1.2.3
Address: 10.1.2.4
Address: 10.1.2.5

SRV Records

dig SRV my-service.default.svc.cluster.local
;; ANSWER SECTION:
my-service.default.svc.cluster.local. 30 IN SRV 0 50 8080 pod-0.my-service.default.svc.cluster.local.
my-service.default.svc.cluster.local. 30 IN SRV 0 50 8080 pod-1.my-service.default.svc.cluster.local.
my-service.default.svc.cluster.local. 30 IN SRV 0 50 8080 pod-2.my-service.default.svc.cluster.local.


Will Requests Be Distributed?

Requests for my-service.default.svc.cluster.local are not inherently load balanced by Kubernetes in the Headless Service.


Key differences from ClusterIP services

For regular ClusterIP services

For Headless Service


Service Comparison Table

Feature Headless Service Regular Service
ClusterIP None Assigned
Load Balancing No Yes
DNS Records Per Pod Single Service
Direct Pod Access Yes No


Conclusion

When accessing my-service.default.svc.cluster.local, traffic is not automatically distributed by Kubernetes.

  1. DNS checks the Pod IP list.
  2. The client decides how to process the corresponding list (e.g., random selection, round robin).
If you need to perform automatic load balancing between multiple Pods, you should use the ClusterIP service instead of the Headless service.

If you do not want to use Headless Service



Reference