Linux Reads the hosts File Before DNS Because nsswitch.conf Lists files First

In progress Linux Networking

Programs on Linux resolve host names through the C library's Name Service Switch, and the hosts: line of /etc/nsswitch.conf sets the order of sources. On most systems it starts with files, so an entry in /etc/hosts answers before any DNS server is asked. Pinning cluster node names there keeps them resolvable when the router's DNS is down, and makes any stale entry silently win over DNS.

The Lookup Order

# /etc/nsswitch.conf
hosts:          files dns

files is /etc/hosts, dns uses the servers in /etc/resolv.conf. Other modules (mdns4_minimal, myhostname, resolve) may appear on the line, but on Debian files stays first. A homelab node list then looks like this:

192.0.2.11    k8s-cp-01
192.0.2.12    k8s-worker-01

Every program on that machine that uses the system resolver gets these addresses, whatever DNS says.

The Cost of Pinning Names

  • Entries go stale silently. After a node changes address, the old line keeps winning, and nothing warns that DNS now says otherwise. Keep the file generated by automation, next to the address plan.
  • The file only covers its own machine. My workstation's entries mean nothing to a pod, whose resolver points to the cluster's DNS (see Pods Should Call Each Other by Service Name, Not Through the Ingress); Kubernetes writes each pod's own /etc/hosts, and adds entries only through hostAliases.
  • It doesn't scale. A few infrastructure names are fine; anything users or many machines need belongs in DNS.

When files has no match, the lookup moves on to DNS, where the node's configured resolvers decide the answer, ISP filtering included (see Pods Inherit the Node's DNS Resolvers, Including Any ISP Blocklist).

References