Wednesday, May 27, 2026

What is a Headless Service in k8s ? Can I expose ClusterIP to external world ?


1. Can I expose a ClusterIP Service to the external world?

Short Answer:

Yes, but not directly. A ClusterIP Service is designed to be internal-only. However, you can still expose it using other resources.

Ways to expose a ClusterIP Service externally:

Method How it works Recommended? Notes
Ingress Most common & recommended Yes (Best) Routes external traffic to your ClusterIP Service
Gateway API Modern replacement of Ingress Yes Future-proof
Proxy through another Service Create a NodePort/LoadBalancer that points to same pods Sometimes Not clean
kubectl port-forward For debugging only No (dev only) Temporary
Directly Not possible No ClusterIP has no external IP
Best Practice:

Create your backend as ClusterIP (which is default), then create an Ingress resource that points to it.

Example:

# Backend Service (ClusterIP)
apiVersion: v1
kind: Service
metadata:
  name: my-backend
spec:
  type: ClusterIP
  selector:
    app: backend
  ports:
  - port: 80
    targetPort: 8080

# Ingress exposing it
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: my-ingress
spec:
  rules:
  - host: api.example.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: my-backend     # ← Pointing to ClusterIP
            port:
              number: 80

2. What is a Headless Service?

A Headless Service is a special type of Kubernetes Service that does not get a ClusterIP.

Key Differences:

Feature Normal Service (ClusterIP) Headless Service
ClusterIP Yes (virtual IP) None (clusterIP: None)
DNS Resolution Resolves to single ClusterIP Resolves to all pod IPs
Load Balancing Done by kube-proxy No load balancing
Use Case General microservices Stateful apps, databases, discovery

When to use Headless Service?

  • StatefulSets (like databases: MongoDB, Cassandra, Elasticsearch)
  • When you need to directly connect to individual Pods
  • For service discovery (getting list of all pod IPs)
  • Leader election, peer-to-peer communication

Example of Headless Service:

apiVersion: v1
kind: Service
metadata:
  name: my-db-headless
spec:
  type: ClusterIP
  clusterIP: None        # ← This makes it headless
  selector:
    app: mongodb
  ports:
  - port: 27017
    targetPort: 27017

When you do DNS lookup for my-db-headless.default.svc.cluster.local , Kubernetes returns all matching Pod IPs instead of one virtual IP.


Summary

  • ClusterIP → Best for internal communication. Can be exposed via Ingress.
  • Headless Service → No ClusterIP, returns individual Pod IPs. Mainly used with StatefulSets.

No comments:

Post a Comment

Kubernetes Topology Spread Constraints

Topology spread constraints are rules in Kubernetes used to control how Pods are distributed across your cluster's failure doma...