CoreDNS and service discovery: ndots, search domains, headless Services, DNS policy

Pod DNS is CoreDNS plus a search list and ndots:5, which turns one short lookup into several queries — the reason DNS is the most common Kubernetes performance surprise.

Read the briefing
About 10 min to read 8 drills

What to remember

  1. ndots:5 multiplies your queries. Short names are tried against every search domain first. A trailing dot or a lower ndots fixes it.
  2. A/AAAA doubling is real. Every lookup can be two queries. Combined with search domains that is 8-10 for one name.
  3. NodeLocal DNSCache exists to keep DNS out of conntrack. On busy nodes, DNS is what fills the conntrack table.
  4. Headless service DNS returns all pod IPs. That is the discovery mechanism for StatefulSets.
  5. CoreDNS is a deployment you must size. Two replicas for a 200-node cluster is a latency incident waiting for the next traffic spike.

The big picture

Cluster DNS is how every pod finds every Service: CoreDNS synthesises records from Services and EndpointSlices, and the kubelet hands each pod a resolv.conf whose search list and ndots setting decide how short names expand. The two failure families interviewers probe are resolution that is wrong (NXDOMAIN from the wrong namespace, missing per-pod names, hostNetwork pods that silently lose cluster DNS) and resolution that is slow or flaky (ndots search storms, the 5-second conntrack race, CoreDNS crashing on a forwarding loop). Good candidates separate those with the rcode and the resolv.conf in front of them.

The mental model

Two halves. In the pod, the resolver takes the name you typed, applies the search list according to ndots, and sends A and AAAA queries in parallel over UDP to the kube-dns ClusterIP. In kube-system, CoreDNS answers anything under cluster.local from its cache of Services and EndpointSlices (authoritative, so NXDOMAIN is final) and forwards everything else to the node's upstream. Every DNS bug lives in one of those halves: read resolv.conf for the first, the CoreDNS log and rcode for the second.

In depth

What resolves to what

Cluster DNS is derived, not configured: CoreDNS watches Services and EndpointSlices and synthesises records on demand from its informer cache. Nothing writes zone files, and no controller "creates" a DNS record.

  • A Service with a ClusterIP gets <svc>.<ns>.svc.cluster.local, an A record (plus AAAA in dual-stack) for the ClusterIP. That record is stable for the life of the Service regardless of what the pods do.
  • A headless Service (clusterIP: None) has no VIP, so the same name returns the IPs of its Ready endpoints, one A record each, rotated by the loadbalance plugin. No Ready pod means no answer.
  • Per-pod names <pod>.<svc>.<ns>.svc.cluster.local exist because the StatefulSet controller sets spec.hostname to the pod name and spec.subdomain to spec.serviceName; the EndpointSlice controller copies that hostname onto the endpoint only when the subdomain equals the Service's name, and CoreDNS serves it. A serviceName that names a Service that does not exist or does not select the pods yields NXDOMAIN for every peer name, the classic reason a fresh etcd or Kafka StatefulSet cannot form a cluster.
  • SRV records _<port>._<proto>.<svc>.<ns>.svc.cluster.local for named ports carry port and target.
  • Pod records <ip-with-dashes>.<ns>.pod.cluster.local exist when the pods option is on; insecure answers without checking that such a pod exists, verified checks the cache.
  • ExternalName Services are a CNAME to the external name; nothing is proxied.

Records carry the TTL configured in the kubernetes plugin (ttl 30 in the standard Corefile; the plugin's own default is 5 s) and CoreDNS's own cache holds answers for up to 30 s, so a Service change is visible cluster-wide within a minute even before client caches expire. When a headless name resolves to fewer pods than you expect, run kubectl get endpointslices -l kubernetes.io/service-name=<svc>: DNS shows exactly what the slice marks ready, nothing more.

Inside the pod: resolv.conf, the search list and ndots

The kubelet writes /etc/resolv.conf into each container according to dnsPolicy. For the default ClusterFirst a pod in namespace shop gets:

search shop.svc.cluster.local svc.cluster.local cluster.local
nameserver 10.96.0.10
options ndots:5

The nameserver is the kube-dns Service ClusterIP (clusterDNS in the kubelet config). The three search suffixes are what make short names work: api becomes api.shop.svc.cluster.local on the first try, api.payments becomes api.payments.svc.cluster.local on the second, and api.payments.svc on the third.

ndots:5 is the rule the resolver uses to pick the order: a name with fewer than five dots is tried with each search suffix first and as an absolute name last. api.example.com has two dots, so a glibc client sends api.example.com.shop.svc.cluster.local, then .svc.cluster.local, then .cluster.local, each as an A and an AAAA query in parallel, collecting six NXDOMAINs from CoreDNS before the real query is forwarded upstream. That is eight queries where two would do, and on busy clusters most of what CoreDNS answers is exactly this.

Three fixes, in order of blast radius. A trailing dot (api.example.com.) marks the name absolute and skips the search list; use it in configuration for external hosts. dnsConfig.options: [{name: ndots, value: "2"}] in the pod template changes the threshold for one workload; two is the sweet spot because api.payments (one dot) still searches first while anything with two or more dots goes absolute first. The CoreDNS autopath plugin walks the search list server-side, but it needs pods verified so CoreDNS can map a source IP to a namespace, which means watching every pod. Do not set ndots:1 cluster-wide: api.payments would be sent upstream first, leaking internal names and adding an external round trip to every cross-namespace call. musl (Alpine) honours search and ndots but ignores several glibc options such as single-request-reopen, so behaviour differs per base image.

CoreDNS and the Corefile

CoreDNS runs as a Deployment (coredns) in kube-system, typically two replicas spread across nodes, behind a ClusterIP Service still called kube-dns for compatibility. The CoreDNS pods use dnsPolicy: Default, so their own /etc/resolv.conf is the node's, and that is where upstream forwarding comes from. The configuration is one ConfigMap, the 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
    loop
    reload
    loadbalance
}

Read it as a chain per query. kubernetes answers anything under cluster.local (and the reverse zones) from its cache of Services and EndpointSlices, returning authoritative NXDOMAIN for names that do not exist; fallthrough lets reverse lookups it cannot answer continue down the chain. Everything else reaches forward, which sends to the nameservers in the node's resolv.conf and health-checks them. cache 30 caches positive and negative answers. ready serves /ready on 8181 and reports ready only once the kubernetes plugin has synced its watches, so a fresh replica does not receive traffic while it would still answer SERVFAIL. reload re-reads the ConfigMap when it changes, so Corefile edits apply within a couple of minutes without a restart, unless the new file fails to parse, which coredns_reload_failed_total and the log tell you. prometheus exposes request, response-by-rcode, forward and cache metrics on 9153.

loop deserves its own paragraph. At startup it sends a random query to itself through the chain; if the query comes back, the forward target is CoreDNS itself. The usual cause is a node whose resolv.conf holds nameserver 127.0.0.53 (the systemd-resolved stub): inside the CoreDNS pod, 127.0.0.53:53 is CoreDNS. The process exits with Loop (127.0.0.1:...) detected for zone "." and the pod sits in CrashLoopBackOff on purpose. The fix is upstream of CoreDNS: point the kubelet at the real file (resolvConf: /run/systemd/resolve/resolv.conf) or give forward explicit addresses.

dnsPolicy and dnsConfig

dnsPolicy selects how the kubelet builds a pod's resolv.conf:

  • ClusterFirst (the default): kube-dns as nameserver, the three cluster search suffixes, ndots:5. Names outside the cluster domain are forwarded by CoreDNS to the node's upstream.
  • Default: copy the node's resolv.conf, whatever the kubelet's resolvConf points at. No cluster names. CoreDNS itself and node agents use it.
  • ClusterFirstWithHostNet: ClusterFirst behaviour for pods with hostNetwork: true. Without it a hostNetwork pod at the default policy is silently treated as Default, so a monitoring agent or CNI daemon that "suddenly" cannot resolve alertmanager.monitoring.svc is almost always this.
  • None: the kubelet writes nothing and dnsConfig must supply everything.

dnsConfig layers on top of any policy: nameservers (up to three), searches (appended to the policy's list) and options such as ndots, timeout, attempts, single-request-reopen or use-vc. A pod that must use corporate resolvers for a private zone but still resolve Services should keep ClusterFirst and get a CoreDNS stanza that forwards that zone, rather than extra nameservers in the pod:

corp.example.internal:53 {
    forward . 10.20.0.53 10.20.1.53
    cache 60
}

The resolver treats a nameserver list as failover, not routing: a query that fails on the first server reaches the second only after a timeout, and a server that answers NXDOMAIN for a zone it does not know stops the search. Conditional forwarding belongs in CoreDNS, where every pod benefits and the forward metrics make it observable. Check what a pod actually got with kubectl exec <pod> -- cat /etc/resolv.conf before theorising; the file is the ground truth of the policy that applied.

Failure modes and how to bisect them

Shrink the problem first. Every name or only external ones? Every pod, one namespace, or one node? Since when, and what changed (node image, NetworkPolicy, CoreDNS ConfigMap, a new StatefulSet)? Then walk the chain from the client outward:

  1. kubectl exec <pod> -- cat /etc/resolv.conf: is the nameserver the kube-dns ClusterIP, are the search suffixes present, did the policy you expected apply (hostNetwork pods!)?
  2. kubectl exec <pod> -- nslookup kubernetes.default.svc.cluster.local 10.96.0.10: query CoreDNS directly with an absolute name. NXDOMAIN means the name is wrong (namespace, typo, a headless Service with no Ready pods). SERVFAIL means CoreDNS could not answer (upstream down for an external name, a replica that has not synced). A timeout means the packet never came back, which is a network problem, not a DNS one.
  3. kubectl -n kube-system get pods -l k8s-app=kube-dns and kubectl -n kube-system get endpointslices -l kubernetes.io/service-name=kube-dns: is anyone behind the kube-dns Service? Zero ready endpoints fails every lookup cluster-wide.
  4. kubectl -n kube-system logs deploy/coredns: loop detection, parse errors after a ConfigMap edit, forward errors and upstream health-check failures.
  5. NetworkPolicy: a default-deny egress policy blocks port 53 unless it allows UDP and TCP 53 to the CoreDNS pods (namespaceSelector on kubernetes.io/metadata.name: kube-system, podSelector on k8s-app: kube-dns). The symptom is lookups timing out only in the policed namespace.
  6. Latency in exact 5 s steps at low CoreDNS load, with conntrack -S | grep insert_failed rising on nodes: the UDP conntrack race between the parallel A and AAAA queries. NodeLocal DNSCache fixes it for glibc and musl alike; single-request-reopen helps only glibc.

Metrics make the bisection quick: coredns_dns_responses_total by rcode (a rising NXDOMAIN share is ndots traffic, a rising SERVFAIL share is upstream trouble), coredns_forward_responses_total and coredns_forward_healthcheck_failures_total by upstream, and coredns_dns_request_duration_seconds for latency. Enable the log plugin only while investigating; it logs every query.

Scaling DNS: fewer queries, closer caches, spread replicas

Cluster DNS sits on the path of nearly every request, so its capacity and failure domain deserve design. Three levers, cheapest first.

Fewer queries. Most load on a busy cluster is search-list NXDOMAIN traffic; fix ndots for external-heavy workloads and use trailing-dot FQDNs in configuration. Applications that resolve on every request instead of honouring TTLs are the other extreme, and applications that cache forever never see a rescheduled headless endpoint. Both are visible per source in coredns_dns_requests_total with the log plugin on briefly.

Closer caches. NodeLocal DNSCache is a DaemonSet that binds a link-local address (169.254.20.10 by default) on every node with NOTRACK rules, so pod queries never enter conntrack; it answers from a local cache and forwards misses to CoreDNS over TCP. It removes the conntrack race, cuts CoreDNS load by the cache hit rate, and keeps a node answering cached names for a short while if CoreDNS is unreachable. The kubelet's clusterDNS points at the link-local address, or the cache also listens on the kube-dns ClusterIP so no pod needs to change.

Spread replicas. Run CoreDNS with pod anti-affinity or topology spread so one node loss cannot take both replicas, size the replica count with the cluster-proportional autoscaler (replicas as a function of nodes and cores), and keep its requests and system-cluster-critical PriorityClass so it is neither starved nor evicted first. Alert on kube-dns ready endpoints dropping below two and on the NXDOMAIN or SERVFAIL share rising, not on raw query rate, which grows with the cluster and says nothing about health.

Myths and facts

Myth: Service names are cluster-global, so curl http://api works from any namespace.

Fact: Names are namespaced. The resolver expands api with the pod's own namespace first, and no search suffix produces a name in another namespace; use api.payments or the full name.

Myth: ndots:5 is a Kubernetes mistake; set ndots:1 everywhere.

Fact: ndots:5 is what makes api, api.payments and api.payments.svc resolve without extra configuration. ndots:1 sends api.payments upstream first, leaking internal names and slowing every cross-namespace call; fix external-heavy workloads with trailing dots or ndots:2 per pod.

Myth: hostNetwork pods resolve Services like any other pod.

Fact: A hostNetwork pod at the default ClusterFirst policy silently falls back to the node's resolv.conf and cannot resolve cluster names; it needs dnsPolicy ClusterFirstWithHostNet.

Myth: Intermittent 5-second DNS latency means CoreDNS is overloaded.

Fact: An exact 5 s quantum is the resolver's retransmit timeout after a dropped UDP packet, usually the conntrack race between the parallel A and AAAA queries. Overload looks like rising latency and SERVFAIL, not a fixed step.

Myth: CoreDNS crashing with a loop error means CoreDNS is broken; remove the loop plugin.

Fact: The loop plugin is a guard: the node's resolv.conf points back at CoreDNS (typically the systemd-resolved stub). Fix the forward target or the kubelet's resolvConf; removing the guard turns a clean crash into a CPU-burning SERVFAIL storm.

Myth: A headless Service resolves to every pod in the StatefulSet.

Fact: Only Ready pods appear unless the Service sets publishNotReadyAddresses: true, and per-pod names exist only when the StatefulSet's serviceName is that Service.

Myth: Editing the CoreDNS ConfigMap requires restarting the CoreDNS pods.

Fact: The reload plugin picks up Corefile changes within a couple of minutes; restart only if reload is absent or the log shows the new file failed to parse.

How pros do it

  • Use trailing-dot FQDNs (or dnsConfig ndots:2) in workloads that call many external hosts, and watch the NXDOMAIN share of coredns_dns_responses_total fall as proof.
  • Run at least two CoreDNS replicas spread across nodes with anti-affinity or topology spread, sized by the cluster-proportional autoscaler; alert when kube-dns has fewer than two ready endpoints.
  • Deploy NodeLocal DNSCache on any cluster with heavy DNS traffic or a 5 s latency step; it removes the conntrack race for every base image and cuts CoreDNS load.
  • Set dnsPolicy: ClusterFirstWithHostNet on every hostNetwork pod that needs cluster names, and lint for it in CI so agents do not lose DNS silently.
  • Give every StatefulSet a governing headless Service whose name equals serviceName, with publishNotReadyAddresses: true, so peer names exist before readiness passes.
  • Ship the DNS egress rule (UDP and TCP 53 to k8s-app: kube-dns pods in kube-system) in the same commit as any default-deny egress NetworkPolicy.
  • Set the kubelet's resolvConf explicitly on node images that run systemd-resolved, and test new node images with a DNS conformance Job before rolling them fleet-wide.
  • Keep cache and the kubernetes plugin ttl deliberate (30 s balances endpoint churn against query load); never raise them to hide a capacity problem, and enable the log plugin only during an investigation.

Questions people ask

Pods cannot resolve anything. Where do you look?

Shrink it first (every name or only external, every pod or one namespace, what changed), then walk the chain: the pod's resolv.conf, an nslookup with an absolute name straight at the kube-dns IP, the CoreDNS pods and the kube-dns endpoints, the CoreDNS log, then NetworkPolicy. Read the rcode as evidence: NXDOMAIN is authoritative (wrong name), SERVFAIL means CoreDNS could not answer (upstream down, replica not synced), a timeout is a dropped packet.

Why are external lookups from my pod slower than from the node?

ndots:5 plus three search suffixes. api.example.com has two dots, so the resolver tries three cluster names first, each as an A and an AAAA query, and only then the absolute name: six NXDOMAINs before the real answer. Fix it per workload (a trailing dot, or dnsConfig ndots:2) — not ndots:1 cluster-wide, which sends api.payments upstream first.

Why does curl http://api work in one namespace and fail in another?

Because names are namespaced and the pod's own search list decides the expansion. In payments, api becomes api.payments.svc.cluster.local; in shop it becomes api.shop.svc.cluster.local, which does not exist, and no other suffix can produce another namespace. Say the fix out loud: api.payments, or the full name in anything that may run elsewhere.

How do I know whether I have the 5-second conntrack race or something else?

Latency in exact 5 s steps, independent of CoreDNS load, on glibc and musl alike, with insert_failed in conntrack -S climbing on the nodes: that is the race between the parallel A and AAAA UDP queries. NodeLocal DNSCache removes it for every image. If latency and SERVFAIL rise with load instead, it is capacity or the upstream.

CoreDNS is in CrashLoopBackOff with a loop error after a node upgrade. Did the upgrade break CoreDNS?

It broke CoreDNS's upstream. The new nodes run systemd-resolved with nameserver 127.0.0.53, CoreDNS inherits that file through dnsPolicy Default, and forwarding to it reaches CoreDNS itself; the loop plugin exits on purpose. Point forward at real resolvers now, then set the kubelet's resolvConf to /run/systemd/resolve/resolv.conf on the image. Never remove the guard.

Can some pods use my company's DNS servers for a private zone?

Yes — in CoreDNS, with a server block for that zone that forwards to the corporate resolvers. Extra nameservers in a pod's dnsConfig give you failover, not routing: the resolver tries the first server, and a wrong answer or a timeout there is what the pod gets.

Do I need to restart pods after changing the CoreDNS ConfigMap?

No. The reload plugin re-reads the Corefile within a couple of minutes. Check the CoreDNS log afterwards: a Corefile that fails to parse is rejected and the old configuration keeps running, which looks like your change silently did nothing.

Why does dig inside the pod fail where nslookup and the application succeed?

dig ignores the search list unless you pass +search, so dig api asks for the absolute name api. and gets NXDOMAIN, while nslookup and glibc apply the suffixes. Use dig +search api or the full name to reproduce what the application sees.

Further reading

Drills · 8

Answer in your head, or out loud, before you reveal. Mark each one: "Again" brings it back, "Got it" counts on your desk.

1 Pick the strongest answer

"curl http://api works from one namespace and fails from another — why?" A pod in shop runs curl http://api/. A healthy Service api exists in payments; there is none in shop. Default dnsPolicy. What happens?

  1. It works: Service names are cluster-wide, and the svc.cluster.local search suffix finds it. svc.cluster.local is a zone, not a namespace; api.svc.cluster.local is not a record for any Service.
  2. curl fails with Could not resolve host: the resolver expands api through the search list, starting with api.shop.svc.cluster.local, and no suffix yields a name that exists; the caller must use api.payments or the full name. Service names are namespaced; the search list only ever inserts the pod's own namespace, so a short name cannot reach another namespace.
  3. It times out: names that are not in the pod's namespace are forwarded to the upstream resolver, which cannot answer. Every candidate name ends in cluster.local, which CoreDNS answers authoritatively with NXDOMAIN in well under a millisecond; nothing is forwarded.
  4. The request resolves but is rejected, because RBAC forbids calling Services in other namespaces. RBAC controls API access, not DNS or pod-to-Service traffic; cross-namespace calls are open unless a NetworkPolicy says otherwise.
  5. It works: CoreDNS looks the Service up in every namespace and returns the first match. The kubernetes plugin answers exactly the name asked; namespace disambiguation happens in the client's search list, not in CoreDNS.
In short

curl fails with 'Could not resolve host' because a short name only expands with the pod's own namespace; use . instead.

Why

The pod's resolv.conf lists <own-ns>.svc.cluster.local, svc.cluster.local and cluster.local as search suffixes, so a bare Service name is only ever completed with the pod's own namespace. Each expansion ends in cluster.local, which CoreDNS answers authoritatively, so the client collects NXDOMAINs and gives up. The interview signal is knowing where namespace scoping is applied (the client's search list) and answering with the form that works: <svc>.<ns>, which the second suffix completes.

The common mistake

Saying 'it works because Service names are cluster-wide' or 'CoreDNS searches every namespace'. The search list is the client's, CoreDNS answers exactly the name asked, and RBAC has nothing to do with traffic.

Read the docs

2 Answer out loud

HTTPS calls from a pod to api.example.com are a few milliseconds slower than the same call from the node, and CoreDNS shows a high NXDOMAIN rate. What is going on, what would you change and where, and what is the catch with the obvious cluster-wide fix? Two to five sentences, as if a staff engineer were timing you.

In short

A strong answer says ndots:5 makes the resolver try three search suffixes first, giving six NXDOMAIN answers, and fixes it per workload with ndots:2 or a trailing dot.

What a strong answer does
  • mechanism: ndots:5 with three cluster search suffixes means the name is tried under each suffix first, each attempt an A plus AAAA pair, so six NXDOMAIN answers precede the real query; quantifies the round trips and ties the NXDOMAIN rate to it.
  • remedy and tradeoff: Chooses between trailing-dot FQDNs in configuration, dnsConfig ndots:2 for the workload, autopath (with its pods verified cost) and NodeLocal DNSCache negative caching; states that ndots:1 cluster-wide sends short cross-namespace names upstream first; names how to verify (NXDOMAIN share of coredns_dns_responses_total, client latency).
  • communication: Leads with the mechanism and a number, then the scoped fix, then the tradeoff and verification, no filler.
Why

Interviewers listen for the search-list arithmetic (three suffixes, A plus AAAA, six wasted queries), for scoping the fix to the workload that needs it, and for the ndots:1 tradeoff that most candidates miss: short cross-namespace names would go upstream first. Reaching for more CoreDNS replicas treats a client-side expansion problem as a server capacity problem.

The common mistake

Treating it as a CoreDNS capacity problem — adding replicas or raising cache — when the extra queries are generated by the client's search list.

Read the docs

3 Read the output

Same curl after the rollout — what does the CoreDNS log show now, and why?

$ kubectl exec -n shop deploy/web -- cat /etc/resolv.conf
search shop.svc.cluster.local svc.cluster.local cluster.local
nameserver 10.96.0.10
options ndots:5

# CoreDNS has the `log` plugin enabled. The pod runs one request:
$ kubectl exec -n shop deploy/web -- curl -s -o /dev/null https://api.example.com/

# CoreDNS log for that request (glibc resolver):
[INFO] 10.244.1.17:41928 - 23514 "A IN api.example.com.shop.svc.cluster.local. udp 56 false 512" NXDOMAIN qr,aa,rd 149 0.000091s
[INFO] 10.244.1.17:41928 - 23515 "AAAA IN api.example.com.shop.svc.cluster.local. udp 56 false 512" NXDOMAIN qr,aa,rd 149 0.000102s
[INFO] 10.244.1.17:52310 - 23516 "A IN api.example.com.svc.cluster.local. udp 51 false 512" NXDOMAIN qr,aa,rd 144 0.000087s
[INFO] 10.244.1.17:52310 - 23517 "AAAA IN api.example.com.svc.cluster.local. udp 51 false 512" NXDOMAIN qr,aa,rd 144 0.000085s
[INFO] 10.244.1.17:37745 - 23518 "A IN api.example.com.cluster.local. udp 47 false 512" NXDOMAIN qr,aa,rd 140 0.000090s
[INFO] 10.244.1.17:37745 - 23519 "AAAA IN api.example.com.cluster.local. udp 47 false 512" NXDOMAIN qr,aa,rd 140 0.000079s
[INFO] 10.244.1.17:60112 - 23520 "A IN api.example.com. udp 33 false 512" NOERROR qr,rd,ra 65 0.012410s
[INFO] 10.244.1.17:60112 - 23521 "AAAA IN api.example.com. udp 33 false 512" NOERROR qr,rd,ra 61 0.011870s

# The pod template is then changed to add:
#   dnsConfig:
#     options:
#       - name: ndots
#         value: "2"
# and the same curl is run again after the rollout.
  1. One line: lowering ndots also disables the AAAA query. The A plus AAAA pair comes from the resolver requesting both address families; ndots only decides the order of candidate names.
  2. Two lines: A and AAAA for api.example.com. answered NOERROR through the forwarder. With two dots the name now meets ndots, so the resolver tries it as an absolute name first and stops on success. ndots is a threshold: names with at least that many dots are tried absolute first; the search list is consulted only if that fails.
  3. The same eight lines: ndots only affects names that contain no dots at all. ndots compares the count of dots in the name with the threshold; api.example.com has two, which satisfies ndots:2 but not ndots:5.
  4. Four lines: the namespace suffix shop.svc.cluster.local is always tried first, then the absolute name. The search list goes first only when the name has fewer dots than ndots; once the threshold is met the absolute name is tried first.
  5. Zero lines: with a lower ndots the pod resolves external names through the node's resolver instead of CoreDNS. The nameserver in resolv.conf is unchanged; every query still goes to CoreDNS, which forwards external names upstream.
In short

The log shows only two lines, A and AAAA for api.example.com., because with ndots:2 the name is tried as an absolute name first.

Why

The first log shows the mechanism in full: api.example.com has two dots, fewer than five, so glibc tries each search suffix first (A and AAAA in parallel), collecting six authoritative NXDOMAINs from the kubernetes plugin before the absolute name is forwarded. With ndots:2 the threshold is met, the absolute name goes first, and the whole exchange is two queries. Interviewers listen for the query count and for knowing which side the fix lives on: the client's resolver options, not CoreDNS.

Read the docs

4 Find what's broken

All three pods start and then crash-loop with cannot resolve etcd-0.etcd-headless.db.svc.cluster.local, although etcd-headless.db.svc.cluster.local resolves to three IPs. Which line is responsible, and what is the fix?

apiVersion: v1
kind: Service
metadata:
  name: etcd-headless
  namespace: db
  labels:
    app: etcd
spec:
  clusterIP: None
  publishNotReadyAddresses: true
  selector:
    app: etcd
  ports:
    - name: peer
      port: 2380
    - name: client
      port: 2379
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: etcd
  namespace: db
spec:
  serviceName: etcd
  replicas: 3
  selector:
    matchLabels:
      app: etcd
  template:
    metadata:
      labels:
        app: etcd
    spec:
      containers:
        - name: etcd
          image: registry.example.com/etcd:3.5
          env:
            - name: ETCD_INITIAL_CLUSTER
              value: "etcd-0=http://etcd-0.etcd-headless.db.svc.cluster.local:2380,etcd-1=http://etcd-1.etcd-headless.db.svc.cluster.local:2380,etcd-2=http://etcd-2.etcd-headless.db.svc.cluster.local:2380"
          ports:
            - name: peer
              containerPort: 2380
            - name: client
              containerPort: 2379
In short

Line 25 is wrong: serviceName must be etcd-headless so the per-pod DNS names exist.

What's broken
  • Line 25: serviceName: etcd does not name the headless Service (etcd-headless). The StatefulSet sets each pod's subdomain to etcd, and the EndpointSlice controller attaches a hostname to an endpoint only when the pod's subdomain equals the Service's name, so CoreDNS has no etcd-0.etcd-headless... records to serve.
Why

Per-pod DNS is a three-party agreement: the StatefulSet writes hostname and subdomain (from serviceName) into each pod, the EndpointSlice controller copies the hostname onto the endpoint only when that subdomain equals the selecting Service's name, and CoreDNS serves <hostname>.<svc>.<ns>.svc.cluster.local from the slice. clusterIP: None (line 9) is required for a headless Service, publishNotReadyAddresses: true (line 10) is exactly what peers need so names exist before readiness, and the peer URLs (line 40) are correct once serviceName matches. The interview signal is explaining why the Service name resolves but the pod names do not, rather than blaming CoreDNS.

Read the docs

5 Scenario: what do you do next?

It is 10:14. Since 10:02 every service in the cluster has been failing outbound calls with Temporary failure in name resolution, and the ingress 5xx alert has fired for all hosts. Between 09:40 and 10:00 the platform team replaced the worker node pool with a new OS image; the old pool is gone. kubectl -n kube-system get deploy coredns shows READY 0/2, and kubectl -n kube-system get pods -l k8s-app=kube-dns shows both pods in CrashLoopBackOff with seven restarts each.

Step 1. You have one command before the incident channel asks what is wrong. Which is it?

  1. Scale CoreDNS to six replicas so that at least some pods come up. Every replica lands on the same new node image and meets the same condition; more crashing pods resolve nothing.
  2. kubectl -n kube-system logs <coredns pod> --previous, to read why the process exits, followed by describe pod for events. A process that has exited seven times has told you why seven times. The last log lines of the previous container are the fastest evidence in the cluster.
  3. kubectl -n kube-system rollout restart deploy/coredns The pods are already restarting on their own; a process that exits on purpose will exit again, and you still will not know why.
  4. Patch every Deployment to dnsPolicy: Default so pods use the node resolver. Cluster-wide, slow, and it breaks Service-name resolution for everything, before the one log line that explains the failure has been read.

Step 2. The log ends with [FATAL] plugin/loop: Loop (127.0.0.1:47316 -> :53) detected for zone ".", see https://coredns.io/plugins/loop#troubleshooting. Query: "HINFO 3245123449876.1287654321.". On a new node, /etc/resolv.conf contains only nameserver 127.0.0.53; the old image listed the VPC resolver. What do you do now?

  1. Edit the coredns ConfigMap so forward targets the real upstream (for example forward . 10.0.0.2), let reload apply it or restart the pods to skip the wait, and confirm resolution from a pod. Fix the kubelet's resolvConf on the node image as a planned change afterwards. The smallest reversible change that restores DNS within a minute. Root cause (the node image's resolver stub) is understood and can be fixed properly once the cluster is serving.
  2. Rebuild the node pool from the previous image and wait for it to come up. Correct eventually, but tens of minutes of continued outage, and it discards the upgrade without understanding it; a one-line Corefile change restores DNS first.
  3. Set hostNetwork: true on the CoreDNS Deployment so it uses the node's network directly. Changes CoreDNS's network position and port binding during an outage without addressing the forward target; an unpredictable side effect is not a mitigation.
  4. Delete the loop line from the Corefile so CoreDNS stops exiting. The loop is real: forwarding to 127.0.0.53 reaches CoreDNS itself, so every external query recurses until it fails. Removing the detector converts a clean crash into a CPU-burning SERVFAIL storm.

Step 3. DNS recovered at 10:21. The postmortem asks for action items. Which set do you propose?

  1. Add a runbook step reminding engineers to check resolv.conf after OS upgrades. A reminder, not a mechanism; the same person under the same time pressure will skip it.
  2. Set kubelet resolvConf: /run/systemd/resolve/resolv.conf explicitly in the node configuration so CoreDNS never inherits the stub; add a DNS conformance Job (resolve a cluster name and an external name from a pod on a new node) to the node-image canary pipeline; alert when kube-dns has fewer than two ready endpoints. Three mechanisms: remove the dependency on OS defaults, verify new images before they take the fleet, and detect the failure minutes earlier next time.
  3. Freeze node OS upgrades until further notice. Trades a known failure for unpatched nodes; the fix is to make upgrades verifiable, not to stop them.
  4. Remove the loop plugin permanently so CoreDNS can never crash this way again. Removes the guard that turned a silent recursion into a clear log line; the next loop would present as a CPU and SERVFAIL storm that is far harder to diagnose.
In short

Read the previous container's log first, then point CoreDNS forward at a real upstream, then fix the kubelet resolvConf on the node image.

Why

CoreDNS runs with dnsPolicy: Default, so forward . /etc/resolv.conf means "whatever the node's resolver file says"; when a node image switches to systemd-resolved, that file says 127.0.0.53, which inside the CoreDNS pod is CoreDNS itself, and the loop plugin exits on purpose rather than recurse. The interview signals are reading the previous container's log before acting, restoring service with a one-line reversible change while understanding why it works, and proposing mechanisms (explicit kubelet resolvConf, image canary with a DNS check, an endpoint alert) instead of reminders.

The common mistake

Deleting the loop line or restarting the Deployment. The loop is real and the plugin is a guard; removing it turns a clean crash into a SERVFAIL storm, and a process that exits on purpose exits again after a restart.

Read the docs

6 Pick the strongest answer

Across a cluster, 0.4% of outbound HTTP calls from pods take exactly 5 s longer than usual (a spike at +5 s, a smaller one at +10 s), on Debian- and Alpine-based images alike, at all hours. CoreDNS p99 latency is 2 ms, its CPU is at 20%, coredns_forward_healthcheck_failures_total is flat, and on the nodes conntrack -S shows insert_failed climbing. What is the mechanism, and which mitigation removes it for every image?

  1. Raise nf_conntrack_max on the nodes so entries are not dropped. The table is not full; insert_failed counts two entries for the same tuple racing, which capacity does not change. A full table logs nf_conntrack: table full.
  2. Add options single-request-reopen through dnsConfig to every pod. It serialises the two queries on glibc and removes the race there, but musl (Alpine) ignores the option, so those pods keep timing out.
  3. CoreDNS is overloaded; add replicas and raise cache to 300. Overload shows as rising latency and SERVFAIL, not a fixed 5 s step; the metrics show CoreDNS idle, and a cached answer still crosses the same UDP path.
  4. The resolver sends the A and AAAA queries in parallel over UDP from one source port; when both packets race through conntrack before an entry exists, one insertion fails and that packet is dropped, so the resolver waits its 5 s timeout and retries. NodeLocal DNSCache removes it for every image: pods query a cache on a link-local address on their own node with NOTRACK rules, and the cache forwards to CoreDNS over TCP. The exact 5 s quantum is the resolver timeout after a drop, and the drop is the conntrack insertion race; taking DNS out of conntrack fixes it regardless of libc.
  5. Set sessionAffinity: ClientIP on the kube-dns Service so a pod always reaches the same CoreDNS replica. The packet is lost on the client node's conntrack insertion before any backend matters; which replica it would have reached is irrelevant.
In short

Two parallel UDP DNS packets race in conntrack and one is dropped, causing a 5 s retry; NodeLocal DNSCache fixes it for every image.

Why

glibc and musl both fire the A and AAAA lookups at once from the same UDP socket; the two packets can race in the kernel's conntrack path, one insertion loses (insert_failed), the packet is dropped, and the resolver waits timeout:5 before retransmitting, which is the +5 s step (two drops give +10 s). NodeLocal DNSCache puts a caching resolver on each node at a link-local address with NOTRACK rules, so the query never enters conntrack, and it talks to CoreDNS over TCP. The interview signal is matching the symptom's exact shape to the resolver timeout and choosing the fix that does not depend on the base image.

Read the docs

7 Quick recall

A hostNetwork DaemonSet (a node agent) cannot resolve Service names while ordinary pods can. Which dnsPolicy fixes it?

In short

Set dnsPolicy: ClusterFirstWithHostNet.

Accepted

ClusterFirstWithHostNet · clusterfirstwithhostnet · dnsPolicy: ClusterFirstWithHostNet

Why

A hostNetwork pod left at the default ClusterFirst policy is silently treated as Default and inherits the node's resolv.conf, which has no cluster search suffixes and no kube-dns nameserver; ClusterFirstWithHostNet restores cluster DNS for it.

Read the docs

8 Pick the strongest answer

A Kafka StatefulSet kafka in namespace msg sits behind a headless Service also named kafka. Brokers advertise kafka-<n>.kafka.msg.svc.cluster.local:9092. During every rolling restart, clients in other namespaces log UnknownHostException: kafka-1.kafka.msg.svc.cluster.local for up to a minute, although kubectl get pod kafka-1 shows it Running the whole time and its IP does not change. What is the mechanism?

  1. CoreDNS caches the old A record for ttl 30, so the new pod IP is invisible for 30 s. The IP did not change, and a stale cached record would return the still-valid old IP, not NXDOMAIN.
  2. The StatefulSet controller deletes the DNS record when it deletes the pod and recreates it only after the replacement is scheduled. No controller writes DNS records; CoreDNS derives them live from Services and EndpointSlices.
  3. Clients in other namespaces must use kafka-1.kafka.msg with ndots tuned; the full svc.cluster.local form is only valid inside the namespace. The full name is valid from anywhere in the cluster; the namespace is part of the name.
  4. The restarted broker is Running but not Ready while it rejoins; the EndpointSlice marks its endpoint ready: false, CoreDNS serves only ready endpoints of a headless Service, so the per-pod A record disappears (NXDOMAIN) until readiness passes. Set publishNotReadyAddresses: true on the governing headless Service, which is what StatefulSet peer names need. Per-pod records are derived from the EndpointSlice's ready endpoints; readiness, not pod existence or IP, decides whether the name resolves.
  5. The kubernetes plugin only serves per-pod records for pods on the same node as the CoreDNS replica that answers. CoreDNS answers from a cluster-wide informer cache of Services and EndpointSlices; node locality plays no part.
In short

The restarting broker is not Ready, so its per-pod DNS record disappears; set publishNotReadyAddresses: true on the headless Service.

Why

A headless Service's records are the ready endpoints of its EndpointSlice, and per-pod names are the hostnames on those endpoints. When the restarted broker's readiness probe has not yet passed, the EndpointSlice controller sets ready: false, the kubernetes plugin stops serving kafka-1.kafka.msg.svc.cluster.local, and clients get NXDOMAIN even though the pod and its IP exist; publishNotReadyAddresses: true makes the controller mark every endpoint ready so peer names are stable through readiness transitions. With a ClusterIP Service this would be invisible because the name resolves to the VIP regardless. The interview signal is connecting readiness to DNS state rather than to "the pod is Running".

Read the docs

Next lesson Ingress and Gateway API: routing, TLS termination, timeouts, and 502/503/504 diagnosis
Drill · CoreDNS and service discovery
0:00

Loading…