0
0
KubernetesHow-ToBeginner · 4 min read

How to Use DNS in Kubernetes: Simple Guide for Service Discovery

In Kubernetes, DNS is used to resolve service names to IP addresses automatically within the cluster using CoreDNS. You can access services by their DNS names like service-name.namespace.svc.cluster.local without needing to know IPs.
📐

Syntax

Kubernetes DNS names follow this pattern: service-name.namespace.svc.cluster.local. Here:

  • service-name: The name of the Kubernetes Service.
  • namespace: The namespace where the service runs.
  • svc: Indicates it is a service.
  • cluster.local: The default cluster domain.

Pods and containers use this DNS to find and connect to services easily.

text
service-name.namespace.svc.cluster.local
💻

Example

This example shows a pod using DNS to connect to a service named my-service in the default namespace.

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: dns-test-pod
  namespace: default
spec:
  containers:
  - name: curl-container
    image: curlimages/curl:7.85.0
    command: ["sleep", "3600"]
💻

Example Usage Inside Pod

After creating the above resources, exec into the pod and use curl with the DNS name:

bash
kubectl exec -it dns-test-pod -n default -- curl http://my-service.default.svc.cluster.local
Output
curl: (7) Failed to connect to my-service.default.svc.cluster.local port 80: Connection refused (Note: This output means DNS resolved but service is not responding because no pod matches selector.)
⚠️

Common Pitfalls

  • DNS resolution fails: CoreDNS might not be running or configured properly.
  • Wrong service name or namespace: DNS names must match exactly.
  • No pods behind service: Service selector does not match any pod labels, so no endpoints exist.
  • Network policies blocking traffic: Pod-to-service communication can be blocked by policies.
bash
### Wrong DNS usage example (will fail)
curl http://wrong-service.default.svc.cluster.local

### Correct DNS usage example
curl http://my-service.default.svc.cluster.local
📊

Quick Reference

Remember these key points for Kubernetes DNS:

  • Use service-name.namespace.svc.cluster.local to reach services.
  • CoreDNS is the default DNS server in Kubernetes clusters.
  • Pods automatically get DNS configured to resolve cluster services.
  • Check service selectors and pod labels to ensure endpoints exist.
  • Use kubectl exec to test DNS inside pods.

Key Takeaways

Kubernetes DNS lets pods find services by name without IPs using CoreDNS.
Service DNS names follow the pattern service.namespace.svc.cluster.local.
Ensure CoreDNS is running and service selectors match pod labels for DNS to work.
Test DNS inside pods using curl or similar tools with the full service DNS name.
Common issues include wrong names, missing pods, or network policies blocking traffic.