Linux Bit by Bit

How DNS works in Kubernetes

Where a Pod sends its DNS queries, which names exist, how short names become full ones, and how CoreDNS decides what to answer. Every command and output comes from a real kubeadm cluster.

Tuesday, 09:15. The storefront team has just shipped a feature that reads stock levels from the inventory Service. It worked in staging. In production, every request fails because inventory doesn’t resolve. The inventory Pods are up and healthy, and nobody touched DNS.

I’ll follow that incident through the post, a few lines at the start of each section. The cause turns out to be small, but finding it means knowing how a lookup travels through the cluster, so that’s where we start.

What’s covered:

  • who answers a Pod’s DNS queries, and how the Pod knows where to send them;
  • which DNS names Kubernetes creates for Services and Pods;
  • how a short name such as inventory becomes a full one, and why ndots matters;
  • the four DNS policies a Pod can have;
  • how to read CoreDNS’s configuration, the Corefile;
  • a step-by-step checklist for when DNS breaks.

The post follows the official Kubernetes pages DNS for Services and Pods, Customizing DNS Service and Debugging DNS Resolution. I ran every command on a kubeadm cluster with Kubernetes v1.37.2 and CoreDNS 1.14.6.

The tools in this post

Tool Its job here
CoreDNS The DNS server that runs inside the cluster and answers Pods’ queries
kubectl Creates test Pods, reads Services, EndpointSlices and logs
dnsutils Pod The test Pod from the Kubernetes docs, an agnhost image with DNS tools
dig Sends one exact DNS query and shows the full answer
nslookup A simpler lookup tool that applies the search list, like most programs do
getent hosts Resolves a name through the C library, exactly as an application would
CoreDNS log plugin Logs every query CoreDNS receives

CoreDNS became the default DNS server in Kubernetes 1.13. Older clusters ran kube-dns, and many clusters add NodeLocal DNSCache on each node. The server software differs, but the way Pods find and query it is the same.

The big picture

09:20. First question: when storefront asks for inventory, who actually answers?

A DNS name is a label for an address. The resolver is the code inside a program that turns names into addresses by asking a DNS server. In Kubernetes, three pieces are involved:

  1. The kubelet writes /etc/resolv.conf into every container. That file tells the resolver which server to ask and how to expand short names.
  2. The kube-dns Service gives the DNS server one stable IP address. The name is a leftover from kube-dns; CoreDNS runs behind it now.
  3. CoreDNS watches the API server and answers questions about Services and Pods from memory. Every other name goes to the resolvers of the node CoreDNS runs on.

The path of a single query:

storefront Pod (namespace web)nameserver 10.96.0.10kubeletwrites /etc/resolv.confquery to port 53 (UDP; TCP if large)Service kube-dns · 10.96.0.10kube-system · a virtual IP, no processkube-proxy picks one ready PodCoreDNS Podkubernetes plugin: *.cluster.localforward plugin: every other nameAPI serverwatched: Services,EndpointSlices, Podsnames outside cluster.localupstream resolversfrom the node's resolv.conf
One query's path. The blue arrows are the query; the answer comes back the same way. Cluster names never leave CoreDNS: the kubernetes plugin answers them from what it watches in the API server. Only other names are forwarded upstream.

When DNS breaks, it breaks at one of those arrows. The checklist at the end of the post walks down them in order.

Who answers: CoreDNS and the kube-dns Service

09:25. The storefront Pods have a nameserver line. Does anything answer on that address?

The kubelet takes two settings from its config file: the DNS Service’s IP and the cluster’s domain. On my control plane node:

grep -E 'clusterDNS|clusterDomain' -A1 /var/lib/kubelet/config.yaml
clusterDNS:
- 10.96.0.10
clusterDomain: cluster.local

Every Pod with default settings gets a resolver file built from those two values. This is the one inside the dnsutils test Pod, in the default namespace:

kubectl exec dnsutils -- cat /etc/resolv.conf
search default.svc.cluster.local svc.cluster.local cluster.local
nameserver 10.96.0.10
options ndots:5

Three lines, three jobs:

  • nameserver is the address to ask: the kube-dns Service.
  • search lists the suffixes to try on short names. The first one contains the Pod’s own namespace.
  • options ndots:5 says when to try those suffixes. It gets its own section below.

10.96.0.10 belongs to an ordinary Service with an ordinary selector:

kubectl -n kube-system get svc kube-dns
kubectl -n kube-system get pods -l k8s-app=kube-dns
NAME       TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)                  AGE
kube-dns   ClusterIP   10.96.0.10   <none>        53/UDP,53/TCP,9153/TCP   35s
NAME                       READY   STATUS    RESTARTS   AGE
coredns-559f6c778d-s8dfp   1/1     Running   0          26s
coredns-559f6c778d-xb757   1/1     Running   0          26s

That’s all “cluster DNS” is: two Pods, a Service, and a file the kubelet writes. A query reaches CoreDNS only if the Service has endpoints, and the Service has endpoints only if its selector matches ready CoreDNS Pods. (Port 9153 is for CoreDNS’s Prometheus metrics.)

The docs suggest this as the first test:

kubectl exec dnsutils -- nslookup kubernetes.default
Server:		10.96.0.10
Address:	10.96.0.10#53

Name:	kubernetes.default.svc.cluster.local
Address: 10.96.0.1

kubernetes.default is the API server’s own Service, so every cluster has it. If this lookup works, the whole path in the diagram works for cluster names. In the incident, it did.

What gets a name

09:30. So CoreDNS answers. Does it have a record for inventory, and under what name?

A DNS specification defines which records Kubernetes creates. A record is one answer stored under a name. Three types matter here:

  • A (or AAAA for IPv6): a name points to an IP address.
  • SRV: a name points to a host name and a port.
  • PTR: the reverse, from an IP address back to a name.

To look at them, I created a Deployment web with three nginx Pods in a namespace shop, and two Services in front of it. web is a normal ClusterIP Service. web-headless is a headless Service (clusterIP: None), which has no virtual IP of its own. Both have a port named http.

A normal Service gets one A record, <service>.<namespace>.svc.<cluster-domain>, pointing at its ClusterIP:

kubectl exec dnsutils -- dig +noall +answer web.shop.svc.cluster.local
web.shop.svc.cluster.local. 30	IN	A	10.107.49.228

From left to right: the name, the TTL (how many seconds a client may cache the answer), the class (IN, for internet), the type, and the value.

A headless Service has the same kind of name, but the answer lists the ready Pods’ IPs:

kubectl exec dnsutils -- dig +short web-headless.shop.svc.cluster.local
10.244.1.4
10.244.1.5
10.244.0.4

The client gets all three and chooses. You want that when a client has to reach one particular Pod, as in a database cluster.

Named ports add SRV records, _<port>._<protocol>.<service>.<namespace>.svc.<cluster-domain>:

kubectl exec dnsutils -- dig +short SRV _http._tcp.web.shop.svc.cluster.local
kubectl exec dnsutils -- dig +short SRV _http._tcp.web-headless.shop.svc.cluster.local
0 100 80 web.shop.svc.cluster.local.
0 33 80 10-244-1-4.web-headless.shop.svc.cluster.local.
0 33 80 10-244-0-4.web-headless.shop.svc.cluster.local.
0 33 80 10-244-1-5.web-headless.shop.svc.cluster.local.

The fields are priority, weight, port and target. For the headless Service, each Pod is its own target, named after its IP.

Pods have names too. CoreDNS still serves the old form, <ip-with-dashes>.<namespace>.pod.<cluster-domain>, because the Corefile’s pods insecure option keeps it for backward compatibility:

kubectl exec dnsutils -- dig +short 10-244-1-5.shop.pod.cluster.local
10.244.1.5

A name based on an IP changes whenever the Pod does. For a stable name, a Pod needs its hostname and subdomain fields set, plus a headless Service in the same namespace named after the subdomain. StatefulSets set this up for you. In namespace data, a StatefulSet db with serviceName: db gives its first Pod this name:

db-0.db.data.svc.cluster.local

The docs add one rule that catches people out: DNS only publishes Pods that are ready. A Pod that fails its readiness probe drops out of the headless Service’s answer, and its own name stops resolving.

Reverse lookups go the other way and return every name that points at an IP:

kubectl exec dnsutils -- dig +short -x 10.244.1.5
10-244-1-5.web-headless.shop.svc.cluster.local.
10-244-1-5.web.shop.svc.cluster.local.

In short, depending on what you want to know:

The question The name to query
What’s the virtual IP of a Service? <svc>.<ns>.svc.cluster.local (A)
Which Pods are behind a headless Service right now? <svc>.<ns>.svc.cluster.local (A, one per ready Pod)
Which port does a named Service port use? _<port>._<proto>.<svc>.<ns>.svc.cluster.local (SRV)
How do I reach one StatefulSet member? <pod>.<svc>.<ns>.svc.cluster.local (A)
Which Service or Pod owns this IP? The IP itself (PTR, with dig -x)

How a short name becomes a full one

09:40. Found it. storefront runs in namespace web, inventory runs in stock, and the code asks for plain inventory. In staging, both apps live in the same namespace.

Programs rarely use full names. They ask for inventory or inventory.stock, and the resolver completes the name using the search list in /etc/resolv.conf. The ndots option decides when it does that:

  1. Count the dots in the name. A name that ends with a dot, such as registry.k8s.io., is already complete: the resolver asks for it exactly as written and stops.
  2. If the name has fewer dots than ndots, the resolver tries it with each search suffix in order, then as written.
  3. If it has at least ndots dots, the resolver tries it as written first, and uses the search list only if that fails.

ndots is just a threshold. It has nothing to do with how many suffixes are in the search list.

So from storefront’s namespace, inventory was tried as inventory.web.svc.cluster.local, then inventory.svc.cluster.local, then inventory.cluster.local. None of those exist. The Service is actually inventory.stock.svc.cluster.local.

The test cluster shows the same thing. From the default namespace, web (which lives in shop) doesn’t resolve:

kubectl exec dnsutils -- nslookup web
Server:		10.96.0.10
Address:	10.96.0.10#53

Non-authoritative answer:
** server can't find web: SERVFAIL

I expected NXDOMAIN (“no such name”) and got SERVFAIL. After the three cluster suffixes, the resolver tried plain web. upstream, and that query failed. The error you see comes from the last attempt, which may not be the one you care about.

storefront’s fix was a one-word change: call inventory.stock. A name that includes the namespace works from anywhere, because the second search suffix turns it into inventory.stock.svc.cluster.local.

Counting dots

Here’s how the rule plays out for names from this post, with the default ndots:5 and a lower ndots:2:

Name Dots ndots:5 ndots:2
inventory 0 search list first search list first
inventory.stock 1 search list first search list first
registry.k8s.io 2 search list first as written first
kubernetes.default.svc 2 search list first as written first
kubernetes.default.svc.cluster.local 4 search list first as written first
registry.k8s.io. trailing dot as written only as written only

The fifth row surprised me. With ndots:5, even a cluster name spelled out in full goes through the search list first, because it has only four dots. From a Pod in default, with CoreDNS’s log plugin on (covered in the Corefile section):

kubectl exec glibc-ndots5 -- getent hosts kubernetes.default.svc.cluster.local
[INFO] 10.244.0.14:46104 "A IN kubernetes.default.svc.cluster.local.default.svc.cluster.local." NXDOMAIN
[INFO] 10.244.0.14:55372 "A IN kubernetes.default.svc.cluster.local.svc.cluster.local." NXDOMAIN
[INFO] 10.244.0.14:42742 "A IN kubernetes.default.svc.cluster.local.cluster.local." NXDOMAIN
[INFO] 10.244.0.14:37618 "A IN kubernetes.default.svc.cluster.local." NOERROR

I trimmed each log line to the client, the question and the result. glibc-ndots5 and glibc-ndots2 are two Debian Pods I started for these tests, so they use Debian’s C library, glibc. The only difference between them is ndots.

Why the default is 5

A high ndots protects names that are relative to the cluster. Look at what happens to kubernetes.default.svc in each Pod:

ndots:5
[INFO] 10.244.0.14:52625 "A IN kubernetes.default.svc.default.svc.cluster.local." NXDOMAIN
[INFO] 10.244.0.14:35427 "A IN kubernetes.default.svc.svc.cluster.local." NXDOMAIN
[INFO] 10.244.0.14:39081 "A IN kubernetes.default.svc.cluster.local." NOERROR

ndots:2
[INFO] 10.244.0.13:39865 "A IN kubernetes.default.svc." NXDOMAIN
[INFO] 10.244.0.13:40032 "A IN kubernetes.default.svc.default.svc.cluster.local." NXDOMAIN
[INFO] 10.244.0.13:52682 "A IN kubernetes.default.svc.svc.cluster.local." NXDOMAIN
[INFO] 10.244.0.13:41367 "A IN kubernetes.default.svc.cluster.local." NOERROR

Both Pods got the right answer. With ndots:2, though, the first attempt was kubernetes.default.svc. as written. That isn’t a cluster name, so CoreDNS forwarded it to the upstream servers outside the cluster before the search list was tried. Every cluster name with two or more dots now costs a trip upstream.

With ndots:5, the in-cluster names people actually write all stay inside the cluster. Even a long SRV name such as _http._tcp.web.shop.svc has only four dots. My reading is that 5 was chosen so these names always work and never leak outside. The price is paid by external names.

What ndots costs

External names pay that price on every lookup. Here’s one lookup of registry.k8s.io from each Pod:

kubectl exec glibc-ndots5 -- getent ahosts registry.k8s.io
kubectl exec glibc-ndots2 -- getent ahosts registry.k8s.io
ndots:5
[INFO] 10.244.0.14:56790 "A IN registry.k8s.io.default.svc.cluster.local." NXDOMAIN
[INFO] 10.244.0.14:56790 "AAAA IN registry.k8s.io.default.svc.cluster.local." NXDOMAIN
[INFO] 10.244.0.14:59295 "A IN registry.k8s.io.svc.cluster.local." NXDOMAIN
[INFO] 10.244.0.14:59295 "AAAA IN registry.k8s.io.svc.cluster.local." NXDOMAIN
[INFO] 10.244.0.14:56673 "AAAA IN registry.k8s.io.cluster.local." NXDOMAIN
[INFO] 10.244.0.14:56673 "A IN registry.k8s.io.cluster.local." NXDOMAIN
[INFO] 10.244.0.14:56869 "A IN registry.k8s.io." NOERROR
[INFO] 10.244.0.14:56869 "AAAA IN registry.k8s.io." NOERROR

ndots:2
[INFO] 10.244.0.13:33004 "AAAA IN registry.k8s.io." NOERROR
[INFO] 10.244.0.13:33004 "A IN registry.k8s.io." NOERROR

Eight queries against two, for the same answer. glibc asks for the IPv4 (A) and IPv6 (AAAA) address on every attempt, so each wasted suffix costs two queries. CoreDNS answers the wasted ones itself, in microseconds, so a single lookup doesn’t matter. A service that calls an external API thousands of times a second sends CoreDNS four times the queries it needs to.

Cutting the extra lookups

There are three common ways to cut those queries, each with a catch:

  • Write external names with a trailing dot. registry.k8s.io. sent just the two real queries from the ndots:5 Pod. It only needs a config change, but the dot can leak into places that don’t expect it. Some HTTP clients pass it on in the Host header or the TLS server name, and the server rejects it. Test it with your client before relying on it.
  • Lower ndots for the Pod. dnsConfig does this without changing the DNS policy (next section). The catch is the one shown in the kubernetes.default.svc example: cluster names with enough dots now go upstream first, and only a fallback saves them. glibc fell back to the search list here. Not every resolver library does, so test the value with the image you actually run.
  • Cache on each node. NodeLocal DNSCache runs a cache on every node, so most queries never reach CoreDNS. The Pod still sends every query; they’re just answered closer.

dig behaves differently from your app. It ignores the search list unless you add +search. That’s useful for exact questions and misleading for “can my app resolve this?”:

kubectl exec dnsutils -- dig +search +noall +answer kubernetes
kubectl exec dnsutils -- dig kubernetes | grep -E 'status|ANSWER:'
kubernetes.default.svc.cluster.local. 30 IN A	10.96.0.1
;; ->>HEADER<<- opcode: QUERY, status: NXDOMAIN, id: 60208
;; flags: qr rd ra ad; QUERY: 1, ANSWER: 0, AUTHORITY: 1, ADDITIONAL: 1

To see what your app sees, run getent hosts <name> inside the app’s container. It uses the same C library as the app.

Choosing a DNS policy for a Pod

10:05. storefront also runs a sidecar. Does that use the same resolver file?

A Pod’s dnsPolicy decides what goes into its /etc/resolv.conf. It has four possible values:

dnsPolicy What the Pod gets
ClusterFirst Cluster DNS with the search list. This is the default.
Default The node’s resolver settings. Despite the name, it’s not the default.
ClusterFirstWithHostNet Cluster DNS for a Pod that uses hostNetwork: true. Not supported on Windows.
None Nothing from Kubernetes. Everything comes from dnsConfig, which must then be set.

All containers in a Pod share one resolver file, so the sidecar sees exactly what the app sees.

With Default on my cluster, a Pod gets the node’s upstream servers and can’t resolve cluster names:

nameserver 77.42.3.28
nameserver 8.8.8.8
nameserver 1.1.1.1
** server can't find web.shop: NXDOMAIN

dnsConfig adds to whatever the policy produced: up to 3 nameservers, extra search domains, and resolver options. Kubernetes allows up to 32 search domains, 2048 characters in total. This Pod keeps ClusterFirst and lowers ndots:

apiVersion: v1
kind: Pod
metadata:
  name: p-ndots
spec:
  dnsConfig:
    options:
    - name: ndots
      value: "2"
  containers:
  - name: c
    image: registry.k8s.io/e2e-test-images/agnhost:2.39
search default.svc.cluster.local svc.cluster.local cluster.local
nameserver 10.96.0.10
options ndots:2

Set dnsPolicy: None without a dnsConfig and the API server rejects the object. I tried it on a test Deployment:

The Deployment "checkout" is invalid: spec.template.spec.dnsConfig: Required value: must provide `dnsConfig` when `dnsPolicy` is None

Inside CoreDNS: the Corefile

10:15. storefront is fixed. I still wanted to know what CoreDNS does with a query once it arrives.

CoreDNS reads its configuration, the Corefile, from the coredns ConfigMap in kube-system. This is the one kubeadm installed on my cluster:

kubectl -n kube-system get configmap coredns -o jsonpath='{.data.Corefile}'
.:53 {
    errors
    health {
       lameduck 5s
    }
    ready
    kubernetes cluster.local in-addr.arpa ip6.arpa {
       pods insecure
       fallthrough in-addr.arpa ip6.arpa
       ttl 30
    }
    prometheus :9153
    forward . /etc/resolv.conf {
       max_concurrent 1000
    }
    cache 30 {
       disable success cluster.local
       disable denial cluster.local
    }
    loop
    reload
    loadbalance
}

.:53 opens a server block that handles every name (. is the root of DNS) on port 53. Each line inside it turns on a plugin, and a query passes through the plugins until one of them answers:

Plugin What it does
errors Logs errors
health, ready Health on port 8080 and readiness on port 8181, used by the Pod’s probes
kubernetes Answers names in cluster.local and reverse lookups from what it watches in the API
prometheus Serves metrics on port 9153
forward Sends every other name to the upstream servers in the node’s /etc/resolv.conf
cache Caches answers for up to 30 seconds. Here it skips cluster.local, which is already in memory.
loop Stops CoreDNS if it detects that its queries come back to itself
reload Notices when the Corefile changes and loads it
loadbalance Shuffles the order of A and AAAA records in each answer

The cache block with its disable lines isn’t in the example on the docs page, so your cluster’s Corefile may differ from the docs too. Check yours.

Some things I learned by editing it:

  • Edits take a while. The kubelet updates the mounted file, and reload checks it periodically. In my tests a change took between 25 seconds and about 2 minutes to reach each Pod. Wait for Reloading complete in the logs of every CoreDNS Pod before you test.
  • A Corefile can have more than one server block. A block such as example.internal:53 { ... } handles only that zone. You could use one to forward that zone to your company’s DNS server. The docs call this a stub domain.
  • A broken upstream only hurts outside names. Cluster names never leave CoreDNS, so the forward target only matters for everything else.

To log every query, add log as the first line inside the server block. It’s noisy; take it out when you’re done.

A debugging checklist

10:30. Writing up the incident. Next time I’d like to start from a checklist.

The official debugging page gives an order that follows the diagram at the top. First, start a test Pod:

kubectl apply -f https://k8s.io/examples/admin/dns/dnsutils.yaml

Then work down the path:

  1. Is it DNS at all? kubectl exec dnsutils -- nslookup kubernetes.default. If this works, cluster DNS works, and the problem is the name you’re using or the Pod you’re in.
  2. What does the Pod’s resolver file say? kubectl exec <pod> -- cat /etc/resolv.conf. Check the nameserver, the search list, ndots, and the Pod’s dnsPolicy.
  3. Are the CoreDNS Pods running and ready? kubectl -n kube-system get pods -l k8s-app=kube-dns.
  4. Do their logs show errors? kubectl -n kube-system logs -l k8s-app=kube-dns.
  5. Does the Service exist, and does it have endpoints? kubectl -n kube-system get endpointslice -l kubernetes.io/service-name=kube-dns. No endpoints means queries go nowhere, however healthy CoreDNS is.
  6. Do queries arrive? Turn on the log plugin and repeat the query.
  7. Can CoreDNS read the API? Its ClusterRole, system:coredns, needs list and watch on Services, EndpointSlices, Pods and Namespaces.
  8. Are you in the right namespace? Short names only search the Pod’s own namespace.

The docs also list two problems on the nodes themselves. On distributions with systemd-resolved, the node’s /etc/resolv.conf can be a stub file that points back at the node. CoreDNS could then forward in a loop. kubeadm avoids that by pointing the kubelet at the real file; on my nodes the kubelet config has resolvConf: /run/systemd/resolve/resolv.conf. And Alpine 3.17 or older can fail on DNS answers larger than 512 bytes, because its resolver had no TCP fallback.

What I took away

  • Cluster DNS is two CoreDNS Pods, one Service and a file the kubelet writes. Each can break on its own.
  • A Service’s name includes its namespace. Across namespaces, use <service>.<namespace>, even if staging happens to put both apps in one.
  • ndots:5 sends nearly every name through the search list first. Handy inside the cluster, wasteful for outside names.
  • The error you see comes from the last attempt. A SERVFAIL for a short name can just mean none of the cluster names existed.
  • dig asks exactly what you type. getent hosts in the app’s container shows what the app gets.
  • Read the Corefile in your own cluster, and give CoreDNS a minute or two after each change.

Try it yourself

Take six on-call tickets on a real two-node kubeadm cluster, from a total DNS outage to a corporate stub domain and an ndots tune-up. Every fix is checked automatically, and the scenarios aren’t the ones in this post.Start the lab on iximiuz Labs

Kubernetes DNS On-Call: Six Broken Lookups