In the default behaviour of Kubernetes we assign as Internal IP address to the service.And with this IP address the service will proxy and load-balance the requests to the pods.We can choose which kind of service type we need while deploying it. These service types are-
- ClusterIP- For exposing the server on cluster-internal IP address
- NodePort- For exposing the service through a static port on the node
- LoadBalancer- to expose the service using an external load-balancer
What is a Headless Service?
When there is no need of load balancing or single-service IP addresses.We create a headless service which is used for creating a service grouping. That does not allocate an IP address or forward traffic.So you can do this by explicitly setting ClusterIP to “None” in the mainfest file, which means no cluster IP is allocated.
For example, if you host MongoDB on a single pod. And you need a service definition on top of it for taking care of the pod restart.And also for acquiring a new IP address. But you don’t want any load balancing or routing. You just need the service to patch the request to the back-end pod. So then you use Headless Service since it does not have an IP.
Kubernetes allows clients to discover pod IPs through DNS lookups. Usually, when you perform a DNS lookup for a service, the DNS server returns a single IP which is the service’s cluster IP. But if you don’t need the cluster IP for your service, you can set ClusterIP to None , then the DNS server will return the individual pod IPs instead of the service IP.Then client can connect to any of them.
Use Cases of Headless Service-
- Create Stateful service
- Deploying RabbitMQ to Kubernetes requires a stateful set for RabbitMQ cluster nodes.
- Deployment of Relational databases
Deployment manifest file:-
apiVersion: apps/v1 kind: Deployment metadata: name: app labels: app: server spec: replicas: 3 selector: matchLabels: app: web template: metadata: labels: app: web spec: containers: - name: nginx image: nginx ports: - containerPort: 80
apiVersion: v1 kind: Service metadata: name: regular-service spec: selector: app: web ports: - protocol: TCP port: 80 targetPort: 8080
apiVersion: v1 kind: Service metadata: name: headless-svc spec: clusterIP: None selector: app: web ports: - protocol: TCP port: 80 targetPort: 8080
Create all resources and run the pod
kubectl create -f deployment.yaml kubectl create -f regular-service.yaml kubectl create -f headless-service.yaml kubectl run temporary --image=radial/busyboxplus:curl -i --tty
Cleanup the used resources
kubectl delete svc regular-service kubectl delete svc headless-svc kubectl delete deployment app kubectl delete po temporary
The DNS server returns three different
IPs for the pods
With a Headless Service, clients can connect to it’s pods by connecting to the service’s DNS name. But using headless services, DNS returns the pod’s IPs and client can connect directly to the pods instead via the service proxy.