0
0
KubernetesHow-ToBeginner · 4 min read

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.local
📊

Quick Reference

ConceptDescriptionExample
Service DNS NameFull DNS name to access a servicemy-service.default.svc.cluster.local
Short NameUse service name alone within same namespacemy-service
NamespaceKubernetes namespace of the servicedefault
Cluster DomainDefault cluster DNS suffixsvc.cluster.local
DNS ProviderKubernetes uses CoreDNS for DNS resolutionCoreDNS

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.