
How Service Discovery Works
When pods are created, scaled, or terminated, Kubernetes updates EndpointSlices to record which pods back each Service. Although you can query these slices via the API server, Kubernetes provides higher-level abstractions to hide this complexity.
Service Discovery Mechanisms
| Mechanism | Description | Pros | Cons |
|---|---|---|---|
| Environment Variables | Kubelet injects service host/port as env vars | Immediate access Zero additional deps | Static at pod start Namespace-scoped |
| DNS | CoreDNS (or kube-dns) auto-creates service records | Dynamic updates Cross-namespace | Requires DNS service Potential lookup latency |
Environment Variables
When a pod is launched, the Kubelet generates environment variables for each Service in the same namespace. These include the service’s ClusterIP, ports, and protocol:Service names are uppercased and dashes become underscores when generating environment variables. The Service must exist before the pod starts, since variables are injected at launch time.
DNS-Based Service Discovery
Deploy a DNS add-on (e.g., CoreDNS) to enable DNS lookups for Services. CoreDNS watches the Kubernetes API and automatically creates DNS records whenever Services change.

DNS Records
By default, Kubernetes creates both A and SRV records for each Service:Shortened DNS Names
Depending on the client’s namespace and search path, you can drop portions of the full DNS name:- Outside the namespace:
my-app.default - Inside the namespace:
my-app
/etc/resolv.conf (configured by the kubelet) controls this:
svc.cluster.local, and finally cluster.local.
If
ndots is set too low, lookups may skip qualified names. Ensure options ndots:5 (or higher) to allow short names in-cluster.Let’s launch a Service on our cluster to see service discovery in action.