How to Use DNS for Service Discovery in Kubernetes
Kubernetes uses an internal
CoreDNS service to provide DNS-based service discovery. You can access services by their service-name.namespace.svc.cluster.local DNS names inside the cluster, allowing pods to find services without hardcoding IPs.Syntax
Kubernetes DNS names follow this pattern inside the cluster:
service-name.namespace.svc.cluster.local: Full DNS name for a service.service-name: Short name usable within the same namespace.namespace: The Kubernetes namespace where the service runs.svc.cluster.local: Default cluster domain suffix.
This DNS name resolves to the service's cluster IP, enabling pods to connect to it.
bash
service-name.namespace.svc.cluster.local
Example
This example shows a pod using curl to access a service by its DNS name inside the cluster.
yaml
apiVersion: v1 kind: Service metadata: name: my-service namespace: default spec: selector: app: my-app ports: - protocol: TCP port: 80 targetPort: 8080 --- apiVersion: v1 kind: Pod metadata: name: test-pod namespace: default spec: containers: - name: curl-container image: curlimages/curl:7.85.0 command: ["sleep", "3600"] --- # After creating these, exec into test-pod and run: # curl my-service.default.svc.cluster.local
Output
curl: (7) Failed to connect to my-service.default.svc.cluster.local port 80: Connection refused
# (If the service is running and reachable, you will get the service response instead.)
Common Pitfalls
- Using wrong DNS names: Forgetting the namespace or using the wrong service name causes resolution failures.
- Accessing services from outside the cluster: DNS names only resolve inside the cluster unless configured otherwise.
- Service not ready: If the service has no endpoints, DNS resolves but connections fail.
Always verify the service and pod status with kubectl get svc and kubectl get pods.
bash
## Wrong DNS usage example (fails):
curl my-service.wrong-namespace.svc.cluster.local
## Correct DNS usage example:
curl my-service.default.svc.cluster.localQuick Reference
| Concept | Description | Example |
|---|---|---|
| Service DNS Name | Full DNS name to access a service | my-service.default.svc.cluster.local |
| Short Name | Use service name alone within same namespace | my-service |
| Namespace | Kubernetes namespace of the service | default |
| Cluster Domain | Default cluster DNS suffix | svc.cluster.local |
| DNS Provider | Kubernetes uses CoreDNS for DNS resolution | CoreDNS |
Key Takeaways
Use the full DNS name
service-name.namespace.svc.cluster.local to access services across namespaces.Within the same namespace, you can use just the service name for DNS resolution.
Kubernetes CoreDNS automatically manages service DNS records inside the cluster.
DNS names only work inside the cluster unless external DNS or ingress is configured.
Check service and pod status if DNS resolves but connections fail.