How to Retrieve All Pod IPs Using Kubernetes Headless Services and DNS
This article explains how Kubernetes Headless Services and DNS can be used to discover and connect to the IP addresses of all Pods behind a Service, with a step‑by‑step example using a MongoDB replica set.
What is a Headless Service?
When a Service is created, Kubernetes can assign it a DNS name. Setting spec.clusterIP to "None" tells Kubernetes not to allocate an IP address, creating a Headless Service that relies on DNS to expose the individual Pod IPs.
Service Types
ClusterIP – default, Service reachable only inside the cluster.
NodePort – exposes the Service on a static port on each node.
LoadBalancer – uses an external cloud load balancer.
By using a Headless Service, the cluster avoids load‑balancing to a single IP and instead creates DNS A/AAAA records for each selected Pod.
DNS Resolution with Headless Services
Kubernetes generates a DNS name for the Service, and other components can resolve it to the set of Pod IPs. The DNS naming follows the pattern <service-name>.<namespace>.svc.cluster.local.
Practical Example
Assume three MongoDB Pods form a replica set. Each Pod is labeled app=mongodb. A Headless Service selects these Pods and provides a DNS name that the application can query.
apiVersion: v1
kind: Service
metadata:
name: mongodb-headless-service
namespace: infrastructure
spec:
selector:
app: mongodb
clusterIP: None
ports:
- port: 27017
targetPort: 27017From a .NET application, the DNS query can be performed with Dns.GetHostAddresses from the System.Net namespace, returning an array of IP addresses that can be used to build a MongoDB connection string.
var addresses = Dns.GetHostAddresses("mongodb-headless-service.infrastructure.svc.cluster.local");
var connectionString = $"mongodb://{string.Join(",", addresses)}";This approach lets the connection string be generated dynamically, so scaling the database cluster does not require manual updates.
Note: MongoDB already supports DNS‑based service discovery via a Headless Service, eliminating the need to manually construct the connection string.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Open Source Linux
Focused on sharing Linux/Unix content, covering fundamentals, system development, network programming, automation/operations, cloud computing, and related professional knowledge.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
