Skip to content

DNS Resolution for Developers: Resolvers, Records, TTL & Caching, /etc/hosts, resolv.conf, Split DNS, DNS in Containers ​

"Host name to address mappings were maintained by the Network Information Center (NIC) in a single file (HOSTS.TXT) which was FTPed by all hosts [RFC-952, RFC-953]." — P. Mockapetris, RFC 1034 Domain Names — Concepts and Facilities, section 2.1, November 1987

Summary: A name becomes an address through a chain of small decisions on your machine (library, nsswitch.conf, /etc/hosts, resolv.conf, caches) before any DNS server is asked, and every link in that chain can be the one that is wrong. Focus: Resolution on a host, the record types a developer meets, TTL and caching at every layer, search domains and ndots, split DNS, containers and Kubernetes, and the Go and PHP behaviour that surprises people. Learning goal: Predict which file, cache or server answered a lookup, explain why dig and your application disagree, and fix stale-IP and slow-first-request incidents without guessing.

This page is the developer's reference for resolving names: what happens between connect("api.internal", 443) and a TCP SYN to an IP. It covers the host resolution path (application, libc getaddrinfo, nsswitch.conf, /etc/hosts, stub resolver, resolv.conf, recursive resolver, root, TLD, authoritative), every record type you meet (A, AAAA, CNAME, ALIAS/ANAME, MX, TXT, SRV, NS, SOA, PTR, CAA, HTTPS/SVCB), TTL and negative caching, search domains and ndots, split-horizon DNS, mDNS and .localhost, UDP, TCP and EDNS0, DoT and DoH, DNS in Docker and Kubernetes, DNS load balancing, the debugging tools, and the Go and Laravel/PHP code that depends on it. The design side (running authoritative DNS, GeoDNS, anycast, DNS as a routing weapon) is IP, DNS, GeoDNS & TTL and is not repeated here. Neighbouring chapters: Network models (the layers), IP addressing (what the answer is), Ports, sockets and connections (what you do with it), Docker networking, Kubernetes networking, VPNs and tunnels (where split DNS usually starts), TLS in practice (why the name matters to certificates) and the network troubleshooting playbook. Pool lifetimes are owned by Connection pooling.

Page map ​

If you are looking forGo to
The one-minute tables: path, records, TTLEverything in one minute
Why DNS bugs feel randomWhy resolution matters
Where /etc/hosts, resolv.conf and the RFCs come fromWhere it comes from
Application to libc to nsswitch to resolver, step by stepThe resolution path on a host
/etc/hosts for local development and its limits/etc/hosts
nameserver, search, ndots, optionsresolv.conf
A, AAAA, CNAME, ALIAS, MX, TXT, SRV, NS, SOA, PTR, CAA, HTTPSRecord types
TTL, browser, OS, resolver, JVM, Go, PHP, connection poolsTTL and caching at every layer
NXDOMAIN caching and "propagation"Negative caching, Propagation myths
Why service works in Kubernetes and the ndots:5 trapSearch domains and ndots
VPN, corporate zones, /etc/resolver, systemd-resolvedSplit DNS
.local, .localhost, .testmDNS and special-use names
512 bytes, TC bit, EDNS0, TCP fallbackUDP, TCP and EDNS0
DoT, DoH, resolver privacyDoT and DoH
127.0.0.11, aliases, --dns, Compose, round robinDNS in Docker
CoreDNS, svc.cluster.local, headless, dnsConfig, NodeLocalDNS in Kubernetes
Round-robin and its limitsDNS-based load balancing
pg_hba.conf, MySQL skip-name-resolveDatabases and DNS
Product by product behaviourPer-product behaviour
Message bytes, error codes, glibc timingMechanics
dig, resolvectl, scutil, getentDebugging toolbox
Fixes in Go and LaravelSolving the classic problems
Symptom to cause tableCommon failures
Single process to multi-regionIn architecture
Reproduce it all with Docker and k3sLab

Everything in one minute ​

The path of one lookup. Every row is unpacked in the resolution path.

StepWhoConfigured byTypical surprise
1. Application cache or poolYour code, JVM, HTTP client, DB poolYour codeAn open connection never re-resolves
2. Name-to-address calllibc getaddrinfo, or Go's own resolverBuild flags, GODEBUG=netdnsGo and curl can disagree on the same host
3. Source ordernsswitch.conf hosts: line/etc/nsswitch.conffiles before dns means /etc/hosts wins
4. Static table/etc/hostsYouOne line shadows real DNS for that name
5. Stub resolverLibrary inside your process/etc/resolv.confsearch and ndots multiply queries
6. Recursive resolverISP, 1.1.1.1, VPC resolver, CoreDNS, 127.0.0.11nameserver linesIt caches until the TTL ends
7. Root, TLD, authoritativeThe DNS treeThe zone ownerThe only place a record is truly changed

The record types.

TypeMapsDeveloper meets it when
A / AAAAname to IPv4 / IPv6Every connection; round-robin sets
CNAMEname to another namewww, SaaS custom domains, ExternalName; cannot sit at the apex
ALIAS / ANAMEapex name to another name (provider feature)You want a CNAME at example.com
MXdomain to mail serversEmail delivery, email:dns validation
TXTname to free textSPF, DKIM, DMARC, domain-ownership checks, ACME challenges
SRVservice name to host, port, priority, weightKubernetes headless services, Consul, SIP, XMPP
NS / SOAzone to its servers / zone parametersDelegation, negative-cache TTL, serials
PTRIP to name (reverse DNS)Mail reputation, pg_hba.conf hostnames, logs
CAAwhich CAs may issue certificatesCertificate issuance failing
HTTPS / SVCBservice parameters, ALPN, ECH hints, aliasHTTP/3 discovery, apex aliasing without CNAME

Where time is spent and kept.

LayerWho owns its lifetimeDefault you should know
Authoritative zoneYou: per-record TTL, SOA minimumYour choice (60 to 3600 s is common)
Recursive resolverThe operator; honours your TTL, may clampCoreDNS cache 30 in k3s
OS or local daemonsystemd-resolved, mDNSResponder, nscd, dnsmasqHonours the TTL
ApplicationThe runtimeGo: none. JVM: networkaddress.cache.ttl. libcurl: 60 s
Connection poolThe pool settingsUntil the socket closes

Why resolution matters to developers ​

Almost every service call starts with a name, and the name-to-IP step is invisible, distributed and cached in places you did not install. When it is right nobody notices; when it is wrong the symptom is rarely "DNS error". It is a 5 second pause on the first request, an old server still receiving traffic an hour after a failover, a container that cannot find its database, or a command that works in one terminal and fails in a service. The fundamental trade-off is between speed and freshness:

Cache longer (high TTL, long-lived sockets)Cache shorter (low TTL, frequent re-resolve)
Fewer lookups, lower latency, less load on resolversMore lookups, more load, more exposure to resolver outages
A resolver outage goes unnoticed for a whileA resolver outage becomes your outage quickly
A change takes the whole TTL (or more) to be seenFailover and migrations are fast
Stable under bursty trafficNeeds a local caching layer (NodeLocal, dnsmasq, systemd-resolved)

The analogy we reuse on this page: asking for a person's phone number. You first check your own address book (/etc/hosts), then the sticky notes on your fridge (caches), then you phone a helpful receptionist (the recursive resolver) who knows how to find anybody: she asks the national directory (root), then the city directory (TLD), then the person's own secretary (authoritative server). Every one of those people writes the number down for a while (the TTL) and will happily read you the old number until their note expires.

Three common misunderstandings, up front ​

  1. "DNS is one lookup against one server." On a host it is a pipeline: library, nsswitch.conf, /etc/hosts, stub resolver, a recursive resolver, and only on a cache miss the root, TLD and authoritative servers. Each stage has its own configuration and its own cache.
  2. "dig shows what my application sees." dig talks to a DNS server directly and ignores /etc/hosts, nsswitch.conf and the search list unless you ask. Your application usually goes through getaddrinfo (or Go's resolver), which does all of those. getent hosts name is the tool that follows the application's path.
  3. "Change the record and the world updates in TTL seconds." The TTL is a hint to caches that obey it. Browsers, JVMs, HTTP clients, connection pools and some resolvers keep answers longer, and open TCP connections never re-resolve at all.

Where it comes from ​

Before DNS, one file did the job. RFC 1034 describes it: "Host name to address mappings were maintained by the Network Information Center (NIC) in a single file (HOSTS.TXT) which was FTPed by all hosts", and it explains why that stopped working: "The total network bandwidth consumed in distributing a new version by this scheme is proportional to the square of the number of hosts in the network." Organizations "had to wait for the NIC to change HOSTS.TXT to make changes visible to the Internet at large." The domain system of RFC 1034 and RFC 1035 (November 1987) replaced the central file with a delegated tree of servers; your /etc/hosts is the surviving fragment of the old design, still consulted first on most systems.

The pieces developers hit later are all patches on that design:

YearDocumentWhat it addedWhy you care
1987RFC 1034, RFC 1035The tree, resource records, TTL, the 512-byte UDP message, the TC bitEverything on this page starts here
1989RFC 1123Requirements for resolvers (section 6.1.3.2), "MUST support UDP, and SHOULD support TCP"Why some people think TCP is optional
1997RFC 2181Clarifications: RRset TTLs, "CNAME RRs may not coexist with other data" at a nameWhy a CNAME cannot sit at the apex
1998RFC 2308Negative caching of NXDOMAIN and NODATA, TTL taken from the SOAWhy a missing name stays missing
2000RFC 2782SRV records (priority, weight, port, target)Service discovery without a load balancer
2013RFC 6762Multicast DNS and .localWhy .local is not for your corporate zone
2013RFC 6761Special-use names: localhost, test, invalid, exampleSafe names for development
2013RFC 6891EDNS(0): larger UDP payloadsWhy 512 bytes is no longer the limit
2016RFC 7766, RFC 7858DNS over TCP requirements; DNS over TLSPrivacy, large answers
2018RFC 8484DNS over HTTPSBrowser-level DNS bypassing the OS
2020RFC 8767Serving stale dataResilience during resolver outages
2023RFC 9460SVCB and HTTPS recordsHTTP/3 hints, aliasing without CNAME limits

Sources are listed in References; every table above comes from the RFC text saved while writing this page.

The concept catalogue ​

Each block follows the same order: plain words, the usual wrong belief, a precise definition, a timeline, real scenarios, what differs per product, and how to use it.

The resolution path on a host Must-know ​

ApplicationGo, PHP, curl, JVMlibc getaddrinfo()or Go pure resolvernsswitch.confhosts: files dns/etc/hostsstatic, first match winsStub resolverno recursion, sends queriesresolv.confnameserver, search, ndotsRecursive resolvercache, honours TTLRoot. NSTLDcom. NSAuthoritativeexample.com. Afilesreads1. ask root: who has com?2. ask TLD: who has example.com?3. ask authoritative: A record?Order and caches that bite you:- an app cache (JVM) or pool pins the IP before step 1- nsswitch order decides if /etc/hosts beats DNS- search + ndots multiply queries at the stub- resolver cache answers until the TTL ends- NXDOMAIN is cached too (negative caching)

In plain words: your program does not talk DNS. It asks the C library (or Go's own resolver) for an address, the library decides which sources to consult and in which order, and only then does it send DNS packets to a server named in resolv.conf.

Common misunderstanding: "My app queries the DNS server I see in resolv.conf." Only after /etc/hosts, any local cache daemon and the search-list rules have had their say, and on macOS /etc/resolv.conf is not even the source of truth. The macOS file itself says: "This file is not consulted for DNS hostname resolution, address resolution, or the DNS query routing mechanism used by most processes on this system. To view the DNS configuration used by this system, use: scutil --dns".

Definition: a stub resolver "cannot perform all resolution itself" and "generally depends on a recursive resolver to undertake the actual resolution function" (RFC 8499). A recursive resolver follows referrals from the root down to the authoritative server and caches the results. An authoritative server holds the zone data. getaddrinfo(3) is the portable call that returns socket addresses for a node name; its failure codes include EAI_NONAME ("The node or service is not known"), EAI_AGAIN ("The name server returned a temporary failure indication. Try again later.") and EAI_FAIL ("The name server returned a permanent failure indication").

text
 1  app:        connect("api.lab.test:443")            -> getaddrinfo("api.lab.test", "443")
 2  libc:       read /etc/nsswitch.conf                -> hosts: files dns
 3  files:      scan /etc/hosts for api.lab.test       -> no match
 4  dns:        read /etc/resolv.conf                  -> nameserver 10.77.0.3, search lab.test, ndots 1
 5  stub:       api.lab.test has 2 dots (>= ndots)     -> query "api.lab.test." first (A and AAAA)
 6  resolver:   cache hit?  yes -> answer with the remaining TTL
 7                          no  -> ask root, TLD, authoritative; cache; answer
 8  libc:       build addrinfo list                    -> [10.0.0.10]
 9  app:        socket(), connect(10.0.0.10:443)       (the name is never looked at again on this socket)

Real scenarios: a developer adds 127.0.0.1 payments.test to /etc/hosts and a Go service sees it while dig payments.test returns NXDOMAIN; a Docker container resolves db through 127.0.0.11 while the host cannot; a VPN installs a per-domain resolver and only some programs see the internal zone.

ComponentLinux (glibc)Alpine (musl)macOSGo (pure)Go (cgo)
Entry pointgetaddrinfogetaddrinfogetaddrinfo via mDNSResponder and scutil resolversnet.Resolvergetaddrinfo
Reads nsswitch.confYesNo (musl has its own simple order)NoYes, for the hosts: orderYes (via glibc)
Reads /etc/hostsYesYesYesYesYes
Per-domain resolversOnly through systemd-resolvedNoYes (/etc/resolver, VPN)NoYes on macOS
Own DNS cacheNo (daemon optional)NoYes (mDNSResponder)NoInherits OS

How to use it: to see what your application sees, use getent hosts NAME on Linux and dscacheutil -q host -a name NAME on macOS; to see what a DNS server says, use dig @server NAME. When they differ, the cause is in steps 2 to 5 above, not in DNS.

/etc/hosts and nsswitch.conf Must-know ​

In plain words: /etc/hosts is a text file that maps names to IPs and is checked before DNS on a normal system. It is the quickest way to point a name at your laptop or a test server, and the quickest way to forget why something is broken a year later.

Common misunderstanding: "/etc/hosts is global." It is per machine and per container: each Docker container gets its own generated file, a Kubernetes Pod gets its own (the kubelet writes it), and a browser with DNS over HTTPS enabled may never read it.

Definition: the order of sources is set by the hosts: line of nsswitch.conf. The man page shows the shape: hosts: dns [!UNAVAIL=return] files is one valid example, and the common default is hosts: files dns, optionally with mdns4_minimal [NOTFOUND=return] first on desktop distributions. Each line of /etc/hosts is an address, a canonical name and aliases; the first match wins; wildcards are not supported.

text
 1  # /etc/nsswitch.conf                       # /etc/hosts
 2  hosts: files mdns4_minimal [NOTFOUND=return] dns
 3                                             127.0.0.1   localhost
 4                                             10.0.0.25   mail.lab.test mail
 5  getaddrinfo("mail.lab.test")  -> files: hit -> 10.0.0.25   (DNS is never asked)
 6  getaddrinfo("web.lab.test")   -> files: miss -> mdns4_minimal: not .local -> dns: asked

Real scenarios: pointing shop.test at 127.0.0.1 for a local Laravel app; testing a new server by mapping the production name to its IP before the DNS change; an old /etc/hosts line left from a migration that now sends production traffic to a decommissioned host; CI containers that need --add-host.

Need/etc/hosts can/etc/hosts cannotBetter tool
One name to one IP on one machineYes
Wildcard *.shop.testNo wildcardsdnsmasq address=/shop.test/127.0.0.1
Different answers per networkStaticSplit DNS, /etc/resolver, systemd-resolved
Test one HTTP client against a new IPAffects the whole machinecURL --resolve, Guzzle CURLOPT_RESOLVE
Share with teammatesLocal onlyA real .test zone in a dev resolver
Docker container--add-host name:ip, Compose extra_hostsThe host's file is not sharedSame

How to use it: Docker documents host-gateway for the host: extra_hosts: ["host.docker.internal:host-gateway"]; "On Linux, host-gateway resolves to the host's IP on the default bridge network. On Mac and Windows, Docker automatically provides this". In the lab on this machine, a container on the default bridge resolved host.docker.internal to 192.168.65.254 and --add-host db.local:10.1.2.3 produced 10.1.2.3 db.local in getent hosts.

resolv.conf: nameserver, search, ndots, options Must-know ​

In plain words: resolv.conf tells the stub resolver which DNS servers to ask and how to expand short names. It is three or four lines, and most DNS pain in containers lives in them.

Common misunderstanding: "More nameserver lines means load balancing and failover." Per resolv.conf(5), the resolver queries them "in the order listed", moving to the next only "if the query times out", and "the default [timeout] is RES_TIMEOUT (currently 5)". A dead first nameserver costs about 5 seconds on every lookup unless options rotate is set.

Definition: the directives that matter (quotes are from resolv.conf(5)):

DirectiveMeaningDefault and limits
nameserver IPA server to query, tried in orderUp to 3 (MAXNS); if none, the local machine
search a b cSuffixes appended to short namesBy default one entry, the local domain; only the last search line counts; unlimited since glibc 2.26, six domains and 256 characters before
domain xObsolete single-entry search
options ndots:n"Sets a threshold for the number of dots which must appear in a name ... before an initial absolute query will be made"Default 1, silently capped to 15
options timeout:nSeconds to wait per serverDefault 5, capped to 30
options attempts:nTries before returning an errorDefault 2, capped to 5
options rotateRound-robin among nameserversOff
options single-requestSend A and AAAA sequentiallyglibc sends them in parallel since 2.9
options no-aaaaSuppress AAAA queries (diagnostics)glibc 2.36 and later
options use-vcUse TCPglibc 2.14 and later
options edns0, trust-adSend EDNS0; trust the AD bit from the serverglibc 2.6 / 2.31
sortlistSort gethostbyname resultsUp to 10 pairs
text
 1  nameserver 10.32.0.10
 2  nameserver 1.1.1.1            # tried only after 10.32.0.10 times out (5 s) and, with attempts:2, a retry
 3  search shop.svc.cluster.local svc.cluster.local cluster.local
 4  options ndots:5 timeout:2 attempts:2
 5  # worst case, dead first server: 2 s x 2 attempts = 4 s before the second server is even tried

Real scenarios: a laptop on VPN with two nameservers where the first is the VPN's and unreachable after sleep (every lookup stalls); a container on the default bridge inheriting a host resolv.conf that points at 127.0.0.53 (a loopback address that means something else inside the container); Kubernetes injecting ndots:5.

ProductWhere the file comes fromWho edits itGotcha
Debian, Ubuntu with systemd-resolvedSymlink to the stub fileresolvectl, netplan, NetworkManagerReal servers are in resolvectl status; the file shows 127.0.0.53
RHEL, FedoraNetworkManagernmcli, nmtuiEditing by hand is overwritten
macOSGeneratedSystem Settings, VPN clientsNot consulted; see scutil --dns
Alpine containersGenerated by the runtimeDocker, kubeletmusl handles search/ndots itself
Docker default bridgeCopy of the host file--dns, --dns-search, --dns-option--dns=127.0.0.1 means the container's own loopback, not the host's
Docker user-defined networknameserver 127.0.0.11, options ndots:0 (observed)DockerNames of containers resolve
Kubernetes PodWritten by kubelet from dnsPolicydnsConfigndots:5 and three search domains

How to use it: read the file inside the environment that fails (docker exec, kubectl exec), not on your laptop. Lab output: a container on a user-defined network showed nameserver 127.0.0.11 and options ndots:0, and the Docker-generated header "Based on host file: '/etc/resolv.conf' (internal resolver)".

Record types a developer meets Must-know ​

In plain words: a DNS record is one fact about a name. The type says which fact: an IPv4 address, an alias, a mail server, a text string, a service port. A lookup always asks for one type.

Common misunderstanding: "A name has one record." A name has a set of records per type (an RRset); one name can have A, AAAA, TXT, MX and CAA at the same time, and an A set with five addresses is one RRset.

Definition and the types one by one. Real answers below were taken from this machine (public names) and from the lab zone lab.test.

TypeWire numberExample (real or lab)Notes
A1api.lab.test. 10 IN A 10.0.0.10IPv4; several records form a round-robin set
AAAA28(RFC 3596)IPv6; getaddrinfo asks for A and AAAA together
CNAME5www.github.com. 953 IN CNAME github.com.Alias; follow-up lookup of the target
NS2example.com. NS hera.ns.cloudflare.com.Delegation to the zone's servers
SOA6example.com. 1798 IN SOA elliott.ns.cloudflare.com. dns.cloudflare.com. 2421050422 10000 2400 604800 1800Serial, refresh, retry, expire, negative TTL
MX155 gmail-smtp-in.l.google.com. (lowest preference first)Mail routing
TXT16"v=spf1 -all" (on example.com)SPF, DKIM, DMARC, verification tokens
SRV335 0 993 imap.gmail.com. (for _imaps._tcp.gmail.com)Priority, weight, port, target
PTR12one.one.one.one. (for 1.1.1.1)In in-addr.arpa / ip6.arpa
CAA257RFC 8659Which CAs may issue
HTTPS / SVCB65 / 64RFC 9460Service parameters and aliasing

A and AAAA. The addresses. Applications normally get both families and race them (Happy Eyeballs, RFC 8305). If AAAA exists but the IPv6 path is broken, you see a delay before the IPv4 fallback; options single-request and no-aaaa exist to diagnose this class of bug, and cURL and Guzzle expose force_ip_resolve (v4/v6).

CNAME and its restrictions ​

In plain words: a CNAME says "this name is just another name for that one". The resolver follows it and answers with the final addresses.

Common misunderstanding: "I can put a CNAME on example.com pointing at my load balancer." You cannot, because a CNAME must be alone at its name: RFC 1034: "If a CNAME RR is present at a node, no other data should be present; this ensures that the data for a canonical name and its aliases cannot be different." RFC 2181 repeats it ("exactly one of the following is true": the name is a CNAME alias or it has other data). The apex of a zone must carry SOA and NS records, so no CNAME there. The same rule forbids MX or TXT next to a CNAME on any name.

text
 1  www.shop.test.   300 IN CNAME  lb-eu.provider.net.      <- fine
 2  lb-eu.provider.net. 60 IN A    203.0.113.7
 3  shop.test.       300 IN SOA    ...                      <- apex already has SOA and NS
 4  shop.test.       300 IN CNAME  lb-eu.provider.net.      <- illegal: CNAME + SOA/NS/MX/TXT
 5  lookup www.shop.test A  -> CNAME lb-eu (TTL 300) + A 203.0.113.7 (TTL 60); the answer is cached per record

Fix: providers sell a workaround, usually called ALIAS, ANAME or CNAME flattening: the provider resolves the target itself and serves A/AAAA records at the apex. Cloudflare documents this as "CNAME flattening ... allows you to use a CNAME record at your zone apex"; AWS Route 53 calls it an alias record ("you can create an alias record at the top node of a DNS namespace"). The cost: the TTL you see is the provider's, the answer is not geo-aware unless the provider makes it so, and it is not part of the DNS standard. RFC 9460's HTTPS/SVCB "AliasMode" is the standard answer for web traffic.

MX, TXT, SPF, DKIM, DMARC, verification ​

RecordWhereExample valuePurpose
MXexample.com10 mail.example.com.Lower preference number is tried first
SPFTXT at example.com"v=spf1 ip4:10.0.0.25 -all" (RFC 7208)Which IPs may send mail for the domain
DKIMTXT at selector._domainkey.example.com"v=DKIM1; k=rsa; p=..." (RFC 6376: "All DKIM keys are stored in a subdomain named _domainkey")Public key for message signatures
DMARCTXT at _dmarc.example.com"v=DMARC1; p=quarantine" (RFC 7489)Policy when SPF/DKIM fail
Domain ownershipTXT at the apex or a random labelA token the SaaS vendor gives youProves control (Google, AWS, ACME _acme-challenge)

A TXT value longer than 255 bytes is stored as several quoted strings in one record; a long record also pushes the response beyond 512 bytes (UDP, TCP and EDNS0). The lab zone carries a 640-byte big.lab.test TXT for exactly that experiment.

SRV: service discovery in the name ​

SRV (RFC 2782) names the host and port of a service: _service._proto.name TTL IN SRV priority weight port target. Lowest priority is tried first; weight splits traffic inside a priority. Kubernetes publishes SRV for named ports (_http._tcp.payments-headless.shop.svc.cluster.local); the lab returned 0 50 8080 10-42-0-4.payments-headless.shop.svc.cluster.local. and one line per pod. Go reads it with net.Resolver.LookupSRV ("sorted by priority and randomized by weight within a priority"); PHP with dns_get_record($name, DNS_SRV). Browsers and most HTTP clients do not use SRV for HTTP, which is why it appears mostly in internal discovery, SIP, XMPP, LDAP, Minecraft and database clients such as MongoDB's mongodb+srv:// URI.

NS and SOA ​

NS records say which servers are authoritative; the parent zone holds the delegation (that is why changing nameservers at your registrar is slow: the parent's NS TTL, often 172800 s, applies. The trace in the lab showed com. 172800 IN NS and example.com. 172800 IN NS). The SOA holds the zone serial, refresh, retry, expire and the negative-caching TTL. Its use as a developer: the SOA serial must increase when you edit a secondary-served zone; its last field and its own TTL control how long NXDOMAIN lives (negative caching).

PTR and reverse DNS ​

Reverse DNS maps an IP to a name under in-addr.arpa (octets reversed) or ip6.arpa. Developers hit it when mail servers reject you for a missing PTR, when logs print hostnames (a reverse lookup per connection is slow), and in databases (pg_hba.conf, MySQL host cache, see Databases and DNS).

CAA ​

CAA (RFC 8659) lists the Certificate Authorities allowed to issue for a name: example.com. CAA 0 issue "letsencrypt.org". CAs must check it before issuing; a forgotten CAA is why an ACME order suddenly fails after a DNS migration. See TLS in practice.

HTTPS and SVCB ​

RFC 9460 defines SVCB (type 64) "used to locate alternative endpoints for a service" and its HTTPS variant (type 65). An HTTPS record can advertise alpn=h3, port, address hints and Encrypted Client Hello keys, and in AliasMode it can alias the apex like a CNAME without the restriction. Browsers query it in parallel with A/AAAA. When dig HTTPS cloudflare.com runs on a clean network it returns the parameter list; on this machine a TUN proxy answered with an A fake address, which is itself a lesson: middleboxes change DNS answers.

Real scenarios (records): an apex domain on a CDN (ALIAS/flattening); onboarding a SaaS with three TXT and two CNAME records; email going to spam for want of SPF/DKIM/DMARC and PTR; a Let's Encrypt order failing on CAA; a gRPC client using SRV for discovery.

RecordGoPHP / Laravel
A / AAAAnet.LookupHost, net.LookupIPgethostbyname (IPv4 only), dns_get_record($h, DNS_A)
CNAMEnet.LookupCNAMEdns_get_record($h, DNS_CNAME)
MXnet.LookupMXgetmxrr, checkdnsrr($d, 'MX'), rule email:rfc,dns
TXTnet.LookupTXTdns_get_record($h, DNS_TXT)
SRVnet.LookupSRVdns_get_record($n, DNS_SRV)
NSnet.LookupNSdns_get_record($h, DNS_NS)
PTRnet.LookupAddrgethostbyaddr, dns_get_record on the reverse name
CAA, HTTPSnot in the stdlib (use a DNS library such as miekg/dns)dns_get_record raw mode or dig in ops tooling

Code: go/lookup/main.go (every lookup through a chosen server, with net.DNSError inspection), go/srv/main.go (SRV discovery) and php/DnsLookups.php (PHP wrappers), all under docs/snippets/foundations/dns-resolution-for-developers/.

go
// Command lookup resolves a name through a chosen DNS server with Go's
// built-in resolver, so you see exactly what the pure-Go path does.
//
//	go run ./lookup -server 127.0.0.1:53 -name api.lab.test
//	GODEBUG=netdns=2 go run ./lookup -name example.com
package main

import (
	"context"
	"errors"
	"flag"
	"fmt"
	"net"
	"os"
	"time"
)

func newResolver(server string) *net.Resolver {
	if server == "" {
		// Zero value: Go decides between the pure-Go and the cgo resolver.
		return net.DefaultResolver
	}
	return &net.Resolver{
		PreferGo: true, // never call libc getaddrinfo
		Dial: func(ctx context.Context, network, _ string) (net.Conn, error) {
			// Ignore the address from /etc/resolv.conf and dial ours.
			d := net.Dialer{Timeout: 2 * time.Second}
			return d.DialContext(ctx, network, server)
		},
	}
}

func main() {
	server := flag.String("server", "", "DNS server host:port (empty = system)")
	name := flag.String("name", "example.com", "name to resolve")
	flag.Parse()

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	r := newResolver(*server)

	start := time.Now()
	addrs, err := r.LookupHost(ctx, *name)
	fmt.Printf("LookupHost %s -> %v (%v) in %s\n", *name, addrs, err, time.Since(start).Round(time.Millisecond))

	if cname, err := r.LookupCNAME(ctx, *name); err == nil {
		fmt.Println("LookupCNAME ->", cname)
	}
	if mx, err := r.LookupMX(ctx, *name); err == nil {
		for _, m := range mx {
			fmt.Printf("MX %d %s\n", m.Pref, m.Host)
		}
	}
	if txt, err := r.LookupTXT(ctx, *name); err == nil {
		fmt.Println("TXT ->", txt)
	}

	var dnsErr *net.DNSError
	if _, err := r.LookupHost(ctx, "does-not-exist."+*name); err != nil {
		if errors.As(err, &dnsErr) {
			fmt.Printf("error: IsNotFound=%t IsTimeout=%t IsTemporary=%t server=%q\n",
				dnsErr.IsNotFound, dnsErr.IsTimeout, dnsErr.IsTemporary, dnsErr.Server)
		} else {
			fmt.Fprintln(os.Stderr, err)
		}
	}
}
go
// Command srv discovers a service with an SRV lookup (RFC 2782) and picks a
// target by priority and weight, the way Consul, Kubernetes headless Services
// and etcd clients publish endpoints.
//
//	go run ./srv -service http -proto tcp -name lab.test -server 127.0.0.1:53
package main

import (
	"context"
	"flag"
	"fmt"
	"net"
	"time"
)

func main() {
	service := flag.String("service", "http", "service label (without underscore)")
	proto := flag.String("proto", "tcp", "tcp or udp")
	name := flag.String("name", "lab.test", "domain")
	server := flag.String("server", "", "DNS server host:port (empty = system)")
	flag.Parse()

	r := net.DefaultResolver
	if *server != "" {
		r = &net.Resolver{PreferGo: true, Dial: func(ctx context.Context, network, _ string) (net.Conn, error) {
			var d net.Dialer
			return d.DialContext(ctx, network, *server)
		}}
	}
	ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
	defer cancel()

	// Looks up _http._tcp.lab.test; results are sorted by priority and
	// randomised by weight within a priority.
	cname, srvs, err := r.LookupSRV(ctx, *service, *proto, *name)
	if err != nil {
		fmt.Println("LookupSRV:", err)
		return
	}
	fmt.Println("canonical:", cname)
	for _, s := range srvs {
		fmt.Printf("priority=%d weight=%d target=%s port=%d\n", s.Priority, s.Weight, s.Target, s.Port)
	}
	if len(srvs) > 0 {
		first := srvs[0]
		fmt.Println("dial ->", net.JoinHostPort(first.Target, fmt.Sprint(first.Port)))
	}
}
php
<?php

declare(strict_types=1);

namespace App\Support\Dns;

/**
 * Thin wrapper over PHP's DNS functions.
 *
 * gethostbyname() goes through libc (nsswitch, /etc/hosts, resolv.conf).
 * dns_get_record(), getmxrr() and checkdnsrr() send DNS queries (resolver
 * library) and return real record data including the remaining TTL.
 */
final class DnsLookups
{
    /** @return list<string> IPv4 addresses, or [] when the name does not resolve */
    public function ipv4(string $host): array
    {
        // gethostbyname() returns the unmodified hostname on failure and has no IPv6 support.
        $ip = gethostbyname($host);

        return $ip === $host ? [] : [$ip];
    }

    /** @return list<string> every A record (a round-robin set is returned whole) */
    public function allA(string $host): array
    {
        $records = dns_get_record($host, DNS_A) ?: [];

        return array_column($records, 'ip');
    }

    /**
     * @return array{ip: string, ttl: int}|null
     */
    public function firstWithTtl(string $host): ?array
    {
        $records = dns_get_record($host, DNS_A) ?: [];
        $first = $records[0] ?? null;

        // 'ttl' is the remaining TTL as seen by the resolver that answered, not the zone's TTL.
        return $first ? ['ip' => $first['ip'], 'ttl' => (int) $first['ttl']] : null;
    }

    /** @return list<array{priority: int, target: string, port: int, weight: int}> */
    public function srv(string $service, string $proto, string $domain): array
    {
        $records = dns_get_record("_{$service}._{$proto}.{$domain}", DNS_SRV) ?: [];
        usort($records, fn (array $a, array $b): int => [$a['pri'], -$a['weight']] <=> [$b['pri'], -$b['weight']]);

        return array_map(fn (array $r): array => [
            'priority' => (int) $r['pri'],
            'target' => (string) $r['target'],
            'port' => (int) $r['port'],
            'weight' => (int) $r['weight'],
        ], $records);
    }

    /** @return list<string> MX hosts ordered by preference */
    public function mxHosts(string $domain): array
    {
        $hosts = [];
        $weights = [];
        if (! getmxrr($domain, $hosts, $weights)) {
            return [];
        }
        array_multisort($weights, $hosts);

        return $hosts;
    }

    /** True when the domain can receive mail: an MX, or (RFC 5321 fallback) an address record. */
    public function canReceiveMail(string $domain): bool
    {
        return checkdnsrr($domain, 'MX') || checkdnsrr($domain, 'A') || checkdnsrr($domain, 'AAAA');
    }

    /** @return list<string> */
    public function txt(string $host): array
    {
        $records = dns_get_record($host, DNS_TXT) ?: [];

        return array_column($records, 'txt');
    }

    public function hasSpf(string $domain): bool
    {
        foreach ($this->txt($domain) as $txt) {
            if (str_starts_with($txt, 'v=spf1')) {
                return true;
            }
        }

        return false;
    }
}

TTL and caching at every layer Must-know ​

Connection pool / keep-alivepins the IP until the socket closesGo http.Transport, HikariCP, PDO persistent, gRPClifetime = idle timeout or max age, NOT the TTLApplication cacheJVM: networkaddress.cache.ttl; Go: none; PHP: none; curl: 60 syou set it, often forever by accidentBrowser cacheChrome and Firefox keep their own cachechrome://net-internals/#dnsabout:networking#dnsOS / local daemonsystemd-resolved, mDNSResponder, nscd, dnsmasqrespects TTL; flush with resolvectl flush-cachesmacOS: dscacheutil -flushcacheRecursive resolverISP, 1.1.1.1, 8.8.8.8, VPC resolver, CoreDNS cacheobeys TTL, may clamp min/max; caches NXDOMAIN by SOAAuthoritative serveryour zone: TTL per record, SOA minimumthe only place the TTL is setWorst-case staleness after a change = sum of every layer that ignores or extends the TTL.Rule of thumb: lower the TTL one full old-TTL BEFORE the change, then change, then raise it again.

In plain words: TTL (time to live) is the number of seconds the owner of a record allows others to remember it. Every cache between you and the authoritative server counts it down, and when it reaches zero the cache must ask again.

Common misunderstanding: "TTL is how long until my change goes live." It is how long a copy that already exists may be kept. A cache that never saw the name has no old copy; a cache that saw it one second before your change keeps the old answer for the whole TTL. And TTL is only respected by layers that implement it: connection pools and some runtimes ignore it.

Definition: the TTL is carried per record in the answer; resolvers return the remaining TTL, so repeated queries show it counting down. RFC 2181 clarifies that an RRset has one TTL and that the value is a 32-bit unsigned number of seconds. After the change the owner sees fresh data at once, while a cache serves the old value until its copy expires.

text
 t+00s  api.lab.test A 10.0.0.10  TTL 10   resolver caches it (cache 300 allows it; the record says 10)
 t+02s  resolver answers 10.0.0.10         remaining TTL 8
 t+06s  resolver answers 10.0.0.10         remaining TTL 4
 t+08s  operator edits the zone: api -> 10.0.0.99; authoritative now answers 10.0.0.99
 t+08s  resolver still answers 10.0.0.10   remaining TTL 2   <- the stale window
 t+10s  resolver copy expired, asks the authoritative server -> 10.0.0.99, TTL 10 again

That timeline is real output from the lab (CoreDNS 1.12.0 as authoritative and as caching resolver, record TTL 10, see Lab): the resolver returned ttl=2 10.0.0.10 while the authoritative server already said 10.0.0.99, then ttl=10 10.0.0.99 two seconds later.

Real scenarios: a failover that flips a database CNAME and the app keeps writing to the old node for hours; a migration planned with TTL 86400 (nothing can be undone for a day); a blue/green switch that works for new users and not for existing connections.

LayerWhat it cachesWho sets the lifetimeWhat to do
AuthoritativeNothing (it is the source)Record TTL, SOA minimumLower the TTL one old-TTL before a planned change
Recursive resolver (ISP, 1.1.1.1, VPC, CoreDNS)Answers and NXDOMAINHonours TTL; may clamp min and maxQuery it directly with dig @IP to see its remaining TTL
OS or local daemonAnswersHonours TTLresolvectl flush-caches, dscacheutil -flushcache (macOS), restart nscd
BrowserIts own host cache, plus DoH settingsBrowserchrome://net-internals/#dns
Application, GoNo cache. Each Dial of a hostname resolves; concurrent identical lookups are merged (singleflight)Your codeAdd a cache only if profiling shows lookup cost
Application, JVMnetworkaddress.cache.ttl (docs: "-1 ... 'cache forever' policy"; default "-1 (forever) if a security manager is installed, and implementation-specific when no security manager is installed"), networkaddress.cache.negative.ttl default 10, networkaddress.cache.stale.ttlSecurity properties, not -DSet networkaddress.cache.ttl=30 (a Java security property)
Application, PHPNo process cache; each gethostbyname or cURL connect resolves (cURL keeps a per-handle cache)libc, libcurlCache in Redis or APCu only if needed
libcurl"By default, libcurl caches this info for 60 seconds" (CURLOPT_DNS_CACHE_TIMEOUT; "failed name resolves are stored ... for half the set timeout period" since 8.16.0)CURLOPT_DNS_CACHE_TIMEOUTZero disables it
Connection pool, keep-alive socketThe result of resolution, as an open TCP connectionPool settingsConnMaxLifetime, IdleConnTimeout, maxTime, MaxConnectionAge

How to use it: treat the effective staleness as the maximum across the stack, not the TTL you set. For critical flips make the lifetime at each layer explicit: TTL 30 to 60 s on the record, no JVM forever-cache, connection lifetime shorter than the failover tolerance. The caching resolver pattern in Go lives in go/cache/resolver.go; the pool bound in go/dbpin/pool.go.

Negative caching (NXDOMAIN and NODATA) Important ​

In plain words: DNS also remembers "this name does not exist" and "this name exists but has no record of that type". If you ask before the record is created, the "no" can stay cached.

Common misunderstanding: "I just created the record, so the first lookup will find it." If anything on the path cached the NXDOMAIN a minute ago (a health check, a typo, a CI job, a browser prefetch), it keeps saying no until the negative TTL ends.

Definition: RFC 2308 states: "Like normal answers negative answers have a time to live (TTL)... the TTL must be carried by another method. This is done by including the SOA record from the zone in the authority section of the reply. When the authoritative server creates this record its TTL is taken from the minimum of the SOA.MINIMUM field and SOA's TTL." Negative caching "should no longer be seen as an optional part of a DNS resolver."

text
 1  t=0    app asks nope.lab.test A          -> resolver asks authoritative -> NXDOMAIN, SOA attached
 2  t=3    operator adds "nope IN A 10.0.0.77" to the zone and bumps the serial
 3  t=4    app asks again                    -> resolver answers NXDOMAIN from cache   (record exists, answer is "no")
 4  t=59   app asks again                    -> still NXDOMAIN, SOA TTL in the answer: 2
 5  t=61   app asks again                    -> NOERROR 10.0.0.77 (negative entry expired)

The timeline is the lab result with CoreDNS 1.12.0 as the caching resolver: the zone's SOA record TTL was 60 and its MINIMUM 5; CoreDNS answered NXDOMAIN for about 60 seconds, not the 5 seconds a strict reading of RFC 2308 ("the minimum of the SOA.MINIMUM field and SOA's TTL") would give. That is the lesson: the server that creates the negative answer decides what TTL travels, and caches differ. Always check with dig +noall +authority.

WhereNegative caching behaviour
Recursive resolvers (BIND, Unbound, public resolvers)RFC 2308 rules, capped by local maximums
CoreDNS cache plugin (observed)Used the SOA record's own TTL (60 s) as received
JVMnetworkaddress.cache.negative.ttl, default 10
libcurlSince 8.16.0, failed resolves are cached for half of the cache timeout
GoNone
BrowsersCache failures briefly

Fix: keep the SOA TTL and minimum small for zones where records appear dynamically (_acme-challenge, per-tenant subdomains); create the record before anything queries it; for CI use a unique name each run.

Propagation myths Important ​

In plain words: "DNS propagation" is not a wave moving across the internet. It is thousands of independent caches whose copies expire at different times.

Common misunderstanding: "It takes 24 to 48 hours." The 48 hours is a registry-era rule of thumb for NS changes at the parent (the TLD zone's NS TTL was 172800 s = 48 h in the trace above). An A record with TTL 60 is fully replaced within about a minute for everything that obeys TTL.

Definition: after a change at the authoritative server, a cache that has a copy will serve it until old_ttl seconds after it was fetched, so the worst case is the old TTL (plus any layer that extends it). Different recursive resolvers fetched at different moments, so a world-wide checker shows a mixture, not a progress bar.

text
 1  T-48h   lower TTL 86400 -> 300 on the record (wait one old TTL so every cache has the short TTL)
 2  T0      change the record
 3  T0+5m   every obeying cache has the new answer; keep the old target alive until then
 4  T+1d    raise the TTL again (optional)
 5  lookups of "what does 8.8.8.8 say" and "what does the authoritative server say" differ during 2-3
ChangeWhat waitsTypical worst case
A/AAAA/CNAME valueThe record's old TTLThe TTL (60 to 3600 s)
NS change at the registrarThe parent zone's NS TTLUp to 48 h with 172800
New record (never queried)Negative cache if anyone askedThe negative TTL
Removing a recordSame as changing itThe old TTL
Any change, long-lived clientsOpen connections and app cachesUntil the client restarts

Fix: plan changes in the order above and verify with dig +trace (authoritative truth) and dig @8.8.8.8 (what that resolver has cached).

Search domains and ndots Must-know ​

In plain words: the search list lets you type a short name (payments) and have the resolver try payments.shop.svc.cluster.local for you. ndots decides whether a name is "short" (try the search list first) or "long enough to be absolute" (try it as is first).

Common misunderstanding: "A name with dots is fully qualified, so it goes straight to DNS." Only a name ending in a dot (api.example.com.) is absolute. With ndots:5 a name like api.example.com has two dots, which is fewer than five, so the stub tries every search suffix first.

Definition: resolv.conf(5): "Resolver queries having fewer than ndots dots (default is 1) in them will be attempted using each component of the search path in turn until a match is found." And: "The default for n is 1, meaning that if there are any dots in a name, the name will be tried first as an absolute name before any search list elements are appended to it." And the warning: "this process may be slow and will generate a lot of network traffic if the servers for the listed domains are not local".

Docker user-defined networkKubernetes node and clusterContainer web127.0.0.11, ndots:0Container dbalias: databaseEmbedded DNS127.0.0.11 in every containernames, aliases, servicesHost resolvers/etc/resolv.conf of the hostDefault bridgecopy of host resolv.confno name lookupother namesCompose project networkservice name = DNS name; replicas share one name (round robin)host.docker.internalhost-gateway, resolves to the host from a containerPodsearch ns.svc.cluster.local ...ndots:5NodeLocal DNSCache169.254.20.10, per nodeCoreDNSService 10.96.0.10Pod networkkube-proxy, DNATkubernetes pluginsvc.cluster.local, podsforward . upstreamnode resolv.conf, corporate DNSFQDN structuremy-svc.my-ns.svc.cluster.localnormal Service -> ClusterIP, headless -> pod IPs_port._proto.my-svc... -> SRV, ExternalName -> CNAME
text
 1  pod:  search shop.svc.cluster.local svc.cluster.local cluster.local     options ndots:5
 2  app:  getaddrinfo("payments")            -> 0 dots < 5 -> shop.svc.cluster.local first -> ClusterIP 10.43.9.76 (1 query pair)
 3  app:  getaddrinfo("api.example.com")     -> 2 dots < 5 -> search list first:
 4          A?/AAAA? api.example.com.shop.svc.cluster.local.   -> NXDOMAIN
 5          A?/AAAA? api.example.com.svc.cluster.local.        -> NXDOMAIN
 6          A?/AAAA? api.example.com.cluster.local.            -> NXDOMAIN
 7          A?/AAAA? api.example.com.                          -> 198.18.1.155      (4th try, 8 packets in total)
 8  app:  getaddrinfo("api.example.com.")    -> trailing dot = absolute -> 1 query pair

The capture in the lab (tcpdump inside a client container with ndots:5 and the three Kubernetes search suffixes) recorded 8 packets to the upstream resolver for one getent hosts api.example.test, and with ndots:1 just 2. The real Kubernetes pod in k3s (v1.31.4, CoreDNS 1.12.0) had search shop.svc.cluster.local svc.cluster.local cluster.local, nameserver 10.43.0.10, options ndots:5, and dig +search +showsearch example.com showed three NXDOMAIN answers before the NOERROR. The Go program go/ndots/ prints the same candidate list and packet counts:

text
ndots:5 -> [api.example.com.shop.svc.cluster.local. api.example.com.svc.cluster.local. api.example.com.cluster.local. api.example.com.] (8 packets until api.example.com answers)
ndots:2 -> [api.example.com. api.example.com.shop.svc.cluster.local. ...] (2 packets until api.example.com answers)

Real scenarios: the first call to a third-party API from a pod is 10 to 100 ms slower than it needs to be; a stub that gets REFUSED or silence instead of a quick NXDOMAIN for the first suffix waits for a timeout at every step (in an early lab run the search walk took 10.02 seconds and getent exited with status 2, because the upstream answered nothing for names outside its zones); some environments hit the CoreDNS rate limits or conntrack races (see Kubernetes).

FixHowTrade-off
Trailing dotCall api.example.com.Code and config change; some TLS/Host-header stacks dislike it
Lower ndots for the PoddnsConfig.options: [{name: ndots, value: "1"}]Short cross-namespace names (payments.shop) then go to DNS as is first and may fail
Full cluster names for internal callspayments.shop.svc.cluster.local.Verbose, immune to search order
Cache locallyNodeLocal DNSCache, dnsmasq, nscd, a Go cacheMore components
Fewer suffixesTrim searchChanges short-name behaviour

How to use it: compute the expansion before blaming DNS; Candidates(name, cfg) in go/ndots/expand.go is a tested model of the rule.

go
// Package ndots reproduces how a stub resolver turns one name into the
// ordered list of queries it will actually send (resolv.conf search + ndots).
package ndots

import (
	"strings"
)

// Config is the part of /etc/resolv.conf that decides the expansion.
type Config struct {
	Search []string
	Ndots  int
}

// Candidates returns the fully-qualified names in the order they are tried.
// A name that ends in a dot is absolute and is never expanded.
func Candidates(name string, c Config) []string {
	if strings.HasSuffix(name, ".") {
		return []string{name}
	}
	var out []string
	asIs := name + "."
	withSearch := make([]string, 0, len(c.Search))
	for _, s := range c.Search {
		withSearch = append(withSearch, name+"."+strings.Trim(s, ".")+".")
	}
	if strings.Count(name, ".") >= c.Ndots {
		// Enough dots: try as an absolute name first, then the search list.
		out = append(out, asIs)
		out = append(out, withSearch...)
	} else {
		// Too few dots: search list first, absolute name last.
		out = append(out, withSearch...)
		out = append(out, asIs)
	}
	return out
}

// PacketsUntil counts the DNS queries sent (A and AAAA per candidate) until
// the candidate that finally answers has been tried. -1 if it is never tried.
func PacketsUntil(name string, c Config, answer string) int {
	for i, cand := range Candidates(name, c) {
		if cand == answer {
			return 2 * (i + 1)
		}
	}
	return -1
}

Split-horizon and split DNS Important ​

In plain words: the same name, or the same company domain, gives different answers depending on who asks and from where, or some domains are answered by a different server than others. Typical: intranet.corp.example only resolves on the VPN, and api.shop.test points at a private IP inside the VPC and a public IP outside.

Common misunderstanding: "If it resolves on my machine it resolves everywhere." Split DNS is per-resolver and per-interface. Your VPN client installs rules ("send corp.example to 10.0.0.2"); a container, a Go binary built without cgo, or a process in another network namespace may not follow them.

Definition: split-horizon means an authoritative or recursive layer returns view-dependent data (internal vs external view). Split DNS (conditional forwarding) means the stub or local resolver routes queries by domain suffix to different servers. systemd-resolved documents the routing rule: "If a name to look up matches ... any of the configured routing domains (search or route-only) of any link ... 'best matching' routing domain is determined: the matching one with the most labels. The query is then sent to all DNS servers ... associated with this 'best matching' routing domain." macOS does it with several resolver clients: scutil --dns on this machine listed per-domain resolvers (domain: local, options: mdns, and 254.169.in-addr.arpa) beside the default one, and resolver(5) explains that files in /etc/resolver are named after the domain they handle.

text
 1  VPN connects:  corp.example -> 10.0.0.2 (internal DNS); everything else -> 1.1.1.1
 2  getaddrinfo("wiki.corp.example")      -> best match corp.example (2 labels) -> 10.0.0.2 -> 10.20.30.40
 3  getaddrinfo("example.com")            -> default route -> 1.1.1.1 -> public address
 4  docker run alpine nslookup wiki.corp.example   -> container resolver (127.0.0.11 -> host servers) -> may bypass the VPN rule
 5  go build CGO_ENABLED=0; run on macOS  -> reads /etc/resolv.conf only -> may not see the per-domain resolver
ToolHow you configure split DNS
systemd-resolved (Linux)resolvectl dns IFACE IP, resolvectl domain IFACE ~corp.example (the ~ makes it a routing-only domain)
macOS/etc/resolver/corp.example containing nameserver 10.0.0.2; VPN clients create them; view with scutil --dns
dnsmasqserver=/corp.example/10.0.0.2 (documented form: --server=/internal.thekelleys.org.uk/192.168.1.1)
CoreDNSA server block per zone with forward; in Kubernetes stubDomains or extra Corefile blocks (custom nameservers)
Docker--dns, --dns-search; the embedded resolver forwards to the host's servers
Cloud VPCResolver endpoints and forwarding rules (Route 53 Resolver, Cloud DNS)

Fix: verify with scutil --dns or resolvectl status, then test from the exact environment that fails (container, pod, runtime). Never assume one tool's view of DNS applies to another; getent hosts or the application's own lookup is the truth.

mDNS, .local, .localhost and other special-use names Good to know ​

In plain words: some names are reserved. .local is for devices announcing themselves on the same network segment without any DNS server; .localhost always means your own machine; .test is safe to invent for development.

Common misunderstanding: "I can use .local for my internal company zone." RFC 6762 reserves it: "any DNS query for a name ending with '.local.' MUST be sent to the mDNS IPv4 link-local multicast address 224.0.0.251", and systemd-resolved's manual says "it is generally recommended to avoid defining '.local' in a DNS server". Putting records there gives slow or failing lookups on some machines (mDNS timeouts); the lab's own dig printed "WARNING: .local is reserved for Multicast DNS" when the Kubernetes search walk used cluster.local.

Definition (RFC 6761 "special-use names"): "The domain 'localhost.' and any names falling within '.localhost.' ... Users may assume that IPv4 and IPv6 address queries for localhost names will always resolve to the respective IP loopback address", and "Name resolution APIs and libraries SHOULD recognize localhost names as special". .test is reserved "for testing", .example and .invalid likewise; .home.arpa (RFC 8375) is the name for home networks.

NameMeaningUse it for
localhost, *.localhostLoopback (many OSes and browsers resolve anything.localhost to 127.0.0.1 without a hosts entry)Local multi-site development: shop.localhost
*.testReserved for tests; never delegatedDev zones with dnsmasq or CoreDNS
*.localmDNS, link-localprinter.local, macbook.local; not corporate DNS
example.com, .example, .invalidDocumentationDocs, tests
*.home.arpaHome network namesHome labs
.dev, .app and other real TLDsReal public TLDsDo not invent names there

How to use it: for a Laravel project served by Herd, Valet, Sail or Caddy, app.test with dnsmasq (address=/test/127.0.0.1, documented as --address=/<domain>/<ipaddr>) is one setup for all projects; app.localhost needs no setup in most browsers but not in every runtime, so check with getent hosts app.localhost.

UDP, TCP and EDNS0 Important ​

In plain words: DNS usually travels in one UDP packet each way. If the answer does not fit, the server sets a "truncated" flag and the client asks again over TCP. A modern extension (EDNS0) lets clients say "my buffer is bigger", avoiding that retry for most answers.

Common misunderstanding: "DNS is UDP-only" (so firewalls drop TCP 53) or "TCP is optional". RFC 7766: "Section 6.1.3.2 of [RFC1123] states: DNS resolvers and recursive servers MUST support UDP, and SHOULD support TCP... However, some implementors have taken the text quoted above to mean that TCP support is an optional feature of the DNS protocol." A blocked TCP/53 breaks big answers (long TXT, DNSSEC, many A records) intermittently.

Definition: RFC 1035 limits UDP messages to 512 octets ("Longer messages are truncated and the TC bit is set"); RFC 6891: "Traditional DNS messages are limited to 512 octets in size when sent over UDP [RFC1035]... EDNS(0) specifies a way to advertise additional features such as larger response size capability, which is intended to help avoid truncated UDP responses, which in turn cause retry over TCP." The lab, with a 738-byte TXT answer:

text
 1  dig +noedns +ignore big.lab.test TXT        flags: qr aa tc rd   ANSWER: 0   MSG SIZE rcvd: 30    (TC set, answer dropped)
 2  dig +noedns +tcp    big.lab.test TXT        flags: qr aa rd      ANSWER: 1   MSG SIZE rcvd: 738   (TCP carries it all)
 3  dig                 big.lab.test TXT        EDNS: udp: 1232      ANSWER: 1   MSG SIZE rcvd: 761   (EDNS0 buffer 1232, fits in UDP)
 4  dig +bufsize=512 +ignore big.lab.test TXT   EDNS: udp: 512       flags: tc   MSG SIZE rcvd: 53     (client buffer too small: TC again)
SettingBehaviour
glibc options edns0Advertises a larger UDP size; use-vc forces TCP
Go pure resolverSends an EDNS0 header (GODEBUG=netedns0=0 disables it; "This can reportedly cause sporadic failures with the DNS server run by some modems and routers") and falls back to TCP on truncation
dig+tcp, +notcp, +bufsize=N, +noedns
Firewalls and security groupsAllow UDP and TCP 53 to your resolver
EDNS buffer sizedig and CoreDNS advertised 1232 bytes in the lab, a size that stays under common path MTUs; larger buffers risk IP fragmentation

DoT, DoH and resolver privacy Good to know ​

In plain words: classic DNS is readable by anyone on the path. DNS over TLS (DoT) and DNS over HTTPS (DoH) wrap the same queries in encryption between you and a chosen resolver.

Common misunderstanding: "DoH hides which sites I visit." It hides the query from the network between you and the resolver; the resolver still sees every name, the destination IP is still visible, and the SNI (unless ECH) names the site.

Definition: RFC 7858 specifies DNS over TLS ("Encryption provided by TLS eliminates opportunities for eavesdropping and on-path tampering with DNS queries in the network"), conventionally on TCP 853. RFC 8484 specifies DoH with media type application/dns-message over HTTPS. RFC 9156 (QNAME minimisation) reduces what each authoritative server in the chain learns.

AspectPlain DNS (53)DoT (853)DoH (443)
EncryptedNoYesYes
Visible to a firewall as DNSYesYes (a dedicated port)No, looks like HTTPS
Who configures itOS, resolv.confsystemd-resolved (DNSOverTLS), Android Private DNS, stubby, unboundBrowsers (Firefox, Chrome "secure DNS"), cloudflared
Respects /etc/hosts and split DNSYesYes, if in the OS stackOften not: the browser asks its own resolver
Developer consequencetcpdump shows namesUse the resolver's logsA browser can ignore your dnsmasq or VPN zone

How to use it: when "it works in curl but not in Chrome" (or the reverse) check whether the browser uses its own DoH resolver; for servers the right place for encryption is between the node and the upstream (a local unbound or CoreDNS forward with TLS), not in every application.

DNS in Docker Must-know ​

In plain words: on a user-defined network, Docker runs a tiny DNS server for you. Containers resolve each other by container name, alias or Compose service name; everything else is forwarded to the host's DNS servers. On the old default bridge there is none of that.

Common misunderstanding: "Containers on the same host can always reach each other by name." Only on a user-defined network. The Docker docs: "Containers that attach to the default bridge network receive a copy of [the host's resolv.conf]. Containers that attach to a custom network use Docker's embedded DNS server. The embedded DNS server forwards external DNS lookups to the DNS servers configured on the host. The embedded DNS server address is 127.0.0.11." And: "Automatic service discovery only resolves custom container names, not default automatically generated names."

Definition and the lab. On a user-defined network dnslab with two containers sharing one alias:

text
 1  $ docker run --rm --network dnslab alpine:3.20 cat /etc/resolv.conf
 2  nameserver 127.0.0.11
 3  options ndots:0
 4  # Based on host file: '/etc/resolv.conf' (internal resolver)
 5  $ nslookup web1              -> Address: 172.18.0.2
 6  $ nslookup web               -> Address: 172.18.0.2 and 172.18.0.3   (alias shared by web1 and web2: round robin)
 7  $ docker run --rm alpine:3.20 nslookup web1     (default bridge)
 8  ** server can't find web1: NXDOMAIN             (nameserver 192.168.65.7, Docker Desktop's resolver)
 9  $ docker run --dns 9.9.9.9 --dns-search corp.test --dns-option ndots:3 ... cat /etc/resolv.conf
10  nameserver 9.9.9.9 / search corp.test / options ndots:3     (the override applies on the default bridge)
11  $ docker run --network dnslab --dns 9.9.9.9 ...   -> still nameserver 127.0.0.11; web1 still resolves

Line 11 is the subtle one: on a user-defined network --dns does not replace 127.0.0.11; it changes the upstream servers that Docker's resolver forwards to. In this setup Docker also set ndots:0 for the internal resolver, so a short name goes to the embedded server as is.

FeatureHowNotes
Container namedocker run --name web1 --network dnslabResolves only on that network
Network alias--network-alias web, Compose networks.NAME.aliasesSeveral containers can share an alias: DNS returns all their IPs
Compose service nameService key is the DNS name on the project networkReplicas (deploy.replicas, --scale) share the service name: round-robin DNS
--dns IP, --dns-search, --dns-optionPer container; Compose dns, dns_search, dns_optDocker: "the container's resolver library determines how it queries them. Some resolvers query the servers in order. Others query them in parallel"; on custom networks "queries upstream servers in order and stops after a successful response or an NXDOMAIN"
host.docker.internal--add-host=host.docker.internal:host-gateway, automatic on Docker DesktopLab: resolved to 192.168.65.254
--add-host name:ipWrites /etc/hosts of that containerLab: 10.1.2.3 db.local
Default bridgeCopy of host resolv.conf, no namesLegacy
Host networkUses the host's resolver

Real scenarios: an app container cannot find db because Compose put it on a different network from the one db joined (see Docker networking); a docker run without --network uses the default bridge and curl http://api fails with "could not resolve host"; a Laravel Sail service names mysql and redis after the Compose services; two replicas behind a service name return round-robin addresses but a client that keeps connections open sticks to one.

How to use it: debug from inside: docker exec CONTAINER cat /etc/resolv.conf, getent hosts NAME, nslookup NAME 127.0.0.11. Replicas: docker compose up --scale api=3 then getent ahosts api lists all three.

DNS in Kubernetes Must-know ​

In plain words: every Pod is configured to ask CoreDNS (a Service with a fixed cluster IP). CoreDNS knows every Service and answers with the cluster IP; for everything else it forwards to the node's upstream DNS.

Common misunderstanding: "Services resolve by name because of Docker-style magic." It is ordinary DNS plus a search list. payments works because the Pod's resolv.conf appends shop.svc.cluster.local to it, as the Kubernetes docs show: "nameserver 10.32.0.10 / search NAMESPACE.svc.cluster.local svc.cluster.local cluster.local / options ndots:5" (NAMESPACE stands for the Pod's namespace).

Definition (from the Kubernetes DNS docs): normal Services get A/AAAA records "of the form my-svc.my-namespace.svc.cluster-domain.example. This resolves to the cluster IP of the Service." Headless Services (no cluster IP) resolve "to the set of IPs of all of the Pods selected by the Service. Clients are expected to consume the set or else use standard round-robin selection from the set." SRV records exist "for named ports". Real cluster (k3s v1.31.4, CoreDNS 1.12.0), from a Pod in namespace shop:

text
 1  $ cat /etc/resolv.conf
 2  search shop.svc.cluster.local svc.cluster.local cluster.local
 3  nameserver 10.43.0.10
 4  options ndots:5
 5  $ dig +search +short payments                       -> 10.43.9.76                      (ClusterIP)
 6  $ dig +short payments.shop.svc.cluster.local         -> 10.43.9.76
 7  $ dig +short payments-headless.shop.svc.cluster.local-> 10.42.0.4 / 10.42.0.2             (pod IPs)
 8  $ dig +short SRV _http._tcp.payments-headless.shop.svc.cluster.local
 9  0 50 8080 10-42-0-4.payments-headless.shop.svc.cluster.local.
10  0 50 8080 10-42-0-2.payments-headless.shop.svc.cluster.local.
11  $ dig ledger-db.shop.svc.cluster.local              -> CNAME db.example.com. (ExternalName), then its A
12  $ getent hosts payments-headless                    -> 10.42.0.2 (one address; glibc/musl pick from the set)
TopicFactSource or observation
FQDN structureSERVICE.NAMESPACE.svc.CLUSTER_DOMAIN (default cluster.local); Pods: 10-42-0-4.shop.pod.cluster.localDocs; lab
dnsPolicyClusterFirst (default), Default (inherit node), ClusterFirstWithHostNet (needed with hostNetwork: true), None (all from dnsConfig)Docs: ""Default" is not the default DNS policy"
dnsConfignameservers (max 3), searches (max 32), options (ndots, edns0, ...)Docs; lab YAML
CoreDNS Corefile (k3s)kubernetes cluster.local in-addr.arpa ip6.arpa { pods insecure ... }, forward . /etc/resolv.conf, cache 30, loop, reload, loadbalancekubectl get cm coredns
ExternalNameA CNAME to an external name; "You may have trouble using ExternalName for ... HTTP and HTTPS" (Host header and TLS name mismatch)Docs
HeadlessclusterIP: None; DNS lists pod IPs; StatefulSets give each Pod a stable nameDocs
NodeLocal DNSCacheDaemonSet caching agent on each node; "Pods will reach out to the DNS caching agent running on the same node, thereby avoiding DNAT rules and connection tracking"; Stable since v1.18Docs
Search list limitsKubernetes limits the search list to 32 entries and 2048 characters totalDocs (stable since v1.28)

Real scenarios: the ndots:5 first-request slowdown for external APIs; intermittent EAI_AGAIN / 5 s DNS timeouts under load, which NodeLocal DNSCache is meant to improve by skipping conntrack; a hostNetwork Pod that cannot resolve Services because it needs dnsPolicy: ClusterFirstWithHostNet; a Go service calling a headless StatefulSet name and getting only one IP.

How to use it: the lab YAML lab/k8s-dns-lab.yaml (namespace, deployment, ClusterIP, headless, ExternalName, a dnsutils Pod). For the networking side (kube-proxy, ClusterIP, CNI) see Kubernetes networking.

DNS-based load balancing and its limits Important ​

In plain words: return several IPs for one name and let clients pick. Cheap, and everywhere: Docker aliases, Kubernetes headless Services, loadbalance in CoreDNS, public round-robin.

Common misunderstanding: "DNS round robin balances load evenly and routes around dead servers." The resolver reorders (or not); clients mostly use the first address, cache the set, keep sockets open, and nothing tells DNS a server died.

Definition: DNS gives out a set of addresses; selection happens in the client. There is no health check, no load awareness, and the TTL is advisory.

text
 1  web.example.test A 10.0.0.1, 10.0.0.2, 10.0.0.3          TTL 30
 2  client A resolves, takes the first -> 10.0.0.1; keeps the connection open for an hour
 3  10.0.0.1 dies at t=100        -> client A errors; DNS still lists 10.0.0.1 until an operator removes it
 4  client B resolves at t=110    -> the resolver cache may still contain .1 (TTL 30) -> 1 in 3 new clients hits a dead host
 5  after the record is removed and TTL passes, only clients that re-resolve notice
ApproachHealth checksRespects TTLTypical use
Plain round-robin A setNoneResolver yes, long-lived clients noCheap spreading, internal tools
Weighted/health-checked DNS (Route 53, Cloudflare LB, NS1)Yes, provider sideShort TTL (often 60 s or lower)Failover between regions; see IP, DNS, GeoDNS
Kubernetes headless ServiceReadiness removes the Pod from the set (after endpoints update)Client dependentgRPC client-side balancing, StatefulSets
SRV with priority and weightNoneYesDiscovery with weights
Layer 4/7 load balancer behind one nameYesName stays stableDefault for public traffic

How to use it: DNS for coarse steering and discovery, a real load balancer for health-aware spreading, and clients that re-resolve (bounded connection age, gRPC MaxConnectionAge). Go's dialer tries every returned address, which is a poor man's failover.

Databases and DNS: pg_hba hostnames and MySQL host cache Good to know ​

In plain words: database servers can use DNS in two places: to check who is connecting (access rules by hostname) and to log or match client hostnames. Both add reverse lookups to the connection path.

Common misunderstanding: "A hostname in pg_hba.conf is resolved when the line is read, like a firewall rule." PostgreSQL does it differently: "that name is compared with the result of a reverse name resolution of the client's IP address ... If there is a match, then a forward name resolution is performed on the host name to check whether any of the addresses it resolves to are equal to the client's IP address. If both directions match, then the entry is considered to match." And it warns: "you should make sure that name resolution is reasonably fast. It can be of advantage to set up a local name resolution cache such as nscd."

Definition: MySQL's host cache stores "IP-to-host name lookups" so that the server "avoids doing a Domain Name System (DNS) lookup for each client connection"; "The server uses the host cache only for non-localhost TCP connections." Running with skip_name_resolve turns hostname use off, which makes account host patterns IP-only.

sql
-- MySQL: IP-based accounts work with skip_name_resolve=ON, hostname-based ones do not
SHOW VARIABLES LIKE 'skip_name_resolve';
CREATE USER 'app'@'10.0.0.%' IDENTIFIED BY 'secret';   -- IP pattern: no reverse DNS needed
CREATE USER 'app'@'%.shop.internal' IDENTIFIED BY 'secret';  -- needs DNS; breaks with skip_name_resolve=ON

-- PostgreSQL: see the rules and whether a hostname rule is in play
SELECT line_number, type, address, auth_method
FROM pg_hba_file_rules
WHERE address !~ '^[0-9a-f:.]+(/[0-9]+)?$' AND address IS NOT NULL;
DatabaseDNS on the connection pathSetting
PostgreSQLReverse then forward lookup for hostname rules; log_hostname adds a reverse lookup per connectionpg_hba.conf, log_hostname
MySQL / InnoDBReverse lookup for hostname accounts, host cacheskip_name_resolve, host_cache_size
SQL Server, OracleThe client resolves the server name from its connection string; DNS is not part of authenticationClient connection string, listener
MongoDBClients resolve seed hosts; mongodb+srv:// reads SRV and TXT recordsConnection string
RedisClient resolves the host once per connection; Sentinel hands out IPs or hostnames (resolve-hostnames)Client, sentinel resolve-hostnames
SQLite, CockroachDBSQLite has no network; CockroachDB nodes advertise addresses that must resolve between nodes--advertise-addr

Fix: use IP-based rules in production, or make sure reverse DNS is correct and fast; for application connections to a database name see Connection pooling and Replication, read replicas and failover.

Per-product behaviour ​

ProductResolver usedCaches DNS?Honours /etc/hostsSearch / ndotsNotes
glibc programs (curl, PHP, Python, Node via libuv getaddrinfo)libc stubNo (unless nscd or systemd-resolved)Yes, via nsswitch.confYesTimeout 5 s, attempts 2 by default
musl (Alpine)musl stubNoYesYes, own implementationBehaves differently from glibc with several nameservers and truncation
macOSmDNSResponder, scutil resolversYesYesPer resolver/etc/resolv.conf is informational
Go, pure resolvernet package, reads resolv.confNoYesYesPreferred on Unix; GODEBUG=netdns=go
Go, cgo resolvergetaddrinfoOSYesOSUsed on macOS, with RES_OPTIONS, LOCALDOMAIN, unsupported nsswitch features; limited to 500 concurrent lookups
JVMInetAddress over libcYes, 30 s class defaults or forever under a security managerYesOSSet networkaddress.cache.ttl
PHP-FPM / CLIlibc; dns_get_record uses the resolver libraryNogethostbyname yesOSEvery request resolves
libcurllibc or c-ares60 s per handleYes (libc)OSCURLOPT_RESOLVE overrides
BrowsersOwn stack, maybe DoHYesUsuallyOwn rulesMay ignore VPN/split DNS
systemd-resolvedDaemon on 127.0.0.53YesYesRouting domainsresolvectl
CoreDNS (Kubernetes)Servercache 30 in k3shosts pluginn/aPod ndots:5
Docker embedded DNS127.0.0.11Forwardsper-container hostsndots:0 observedCustom networks only

Mechanics ​

One DNS message on the wire ​

Real capture from the lab client (tcpdump -XX, query api.lab.test A, 30 bytes of DNS):

text
 1  0x002a: 15e7 0020 0001 0000 0000 0000      ID=0x15e7  flags=0x0020  QD=1 AN=0 NS=0 AR=0
 2  0x0036: 03 61 70 69 03 6c 61 62 04 74 65 73 74 00   3"api" 3"lab" 4"test" 0   (length-prefixed labels)
 3  0x0044: 0001 0001                           QTYPE=A (1)  QCLASS=IN (1)
 4  response flags 0x8400 = QR=1 (response) + AA=1 (authoritative); ANCOUNT=1; the answer name is
 5  the compression pointer c00c in a real server, here spelled out; TTL 0x0000000a = 10; RDLENGTH 4; RDATA 0a00000a = 10.0.0.10

Header flags: QR, Opcode, AA (authoritative), TC (truncated), RD (recursion desired), RA (recursion available), RCODE. 0x0020 in the query is the AD bit dig sets.

Response codes and what the library reports ​

SituationWireGo (net.DNSError)glibcPHP
Name does not existRCODE 3 NXDOMAIN ("Name Error", RFC 1035)IsNotFound=true, "no such host"EAI_NONAMEgethostbyname returns the input
Exists, no data of that typeRCODE 0, empty answer (NODATA)IsNotFoundEAI_NODATA or NONAMEempty array
Server failureRCODE 2 SERVFAILIsTemporary=trueEAI_AGAIN or EAI_FAILfalse
RefusedRCODE 5 REFUSEDerrorEAI_FAILfalse
No replynoneIsTimeout=trueEAI_AGAIN after timeout x attemptsslow false

Time budget of a failed lookup ​

glibc: each nameserver gets timeout seconds, the list is walked attempts times: two servers, defaults: 5 s x 2 attempts x 2 servers can approach 20 s per name per candidate, times the search-list length, which is why a dead resolver looks like a hung application. Go: its resolver has its own timeout and honours the context deadline; always pass a context with a deadline.

Debugging toolbox ​

QuestionCommandWhat to read
What does the application path return?getent hosts NAME (Linux), dscacheutil -q host -a name NAME (macOS)Source order, /etc/hosts included
What does DNS itself say?dig NAME, dig +short NAME, dig @1.1.1.1 NAMEStatus, remaining TTL, AUTHORITY section
Authoritative truthdig +trace NAMERoot, TLD, authoritative hops and their TTLs
Which server answered?dig footer SERVER:The resolver actually used
Search list effectdig +search +showsearch NAMEThe expanded names tried
Other toolsnslookup NAME, host NAMESame data, different defaults; nslookup applies the search list
Linux resolver stateresolvectl status, resolvectl query NAME, resolvectl flush-caches, resolvectl statisticsPer-link servers, routing domains, cache hits
macOS resolver statescutil --dns, dscacheutil -flushcachePer-domain resolvers, mdns flags
Cachesnscd -g, systemd-resolved statsWhether a daemon holds the answer
GoGODEBUG=netdns=2 ./appusing the Go DNS resolver, hostLookupOrder(NAME) = files,dns
Packetstcpdump -n -i any port 53Query count, retries, NXDOMAIN walks

Real output from this machine: dig +trace went . -> com. -> example.com. -> A with Received 823 bytes from 198.18.0.2 for the root hop. The 198.18.x.x addresses are the signature of a TUN proxy that fakes DNS on this laptop; on a normal network those hops show real root and TLD server IPs. scutil --dns showed resolver #1 and #2 on utun4 with nameserver 198.18.0.2, and resolver #3 domain: local, options: mdns.

Solving the classic problems ​

Stale IP after a failover ​

SolutionHowAdvantageCost
Short TTL on the record30 to 60 sSimpleMore lookups; does nothing for open sockets
Bound connection ageSetConnMaxLifetime, IdleConnTimeout, Horizon maxTime, gRPC MaxConnectionAgeForces re-dial and re-resolveReconnect churn
Re-resolving dialerCache with TTL and CloseIdleConnections on a timerFine controlOwn code
Reconnect on "wrong node" errorsTreat read-only and getaddrinfo errors as reconnect triggersSelf-healsMust retry safely
Move the change below DNSVirtual IP, proxy, PgBouncer/ProxySQLNo client changeAnother hop

Go: go/dbpin/pool.go (SetConnMaxLifetime(30s)), go/cache/resolver.go (positive, negative and stale caching with merged concurrent lookups) and go/transport/main.go (dialer that resolves through the cache and tries each address; idle connections closed on a timer). The cache tests simulate the clock: 3 lookups hit upstream once, expiry after 6 s picks up 10.0.0.99, NXDOMAIN is cached for NegTTL, and a failing upstream serves the stale answer.

go
// Package cache is a small caching resolver for services that look up the
// same few names on every request. Go's net package has no DNS cache and the
// stdlib does not expose record TTLs, so the TTL here is a policy you choose.
package cache

import (
	"context"
	"errors"
	"net"
	"sync"
	"time"
)

// Lookuper is what *net.Resolver already implements.
type Lookuper interface {
	LookupHost(ctx context.Context, host string) ([]string, error)
}

type entry struct {
	addrs   []string
	err     error
	expires time.Time
}

type call struct {
	done  chan struct{}
	addrs []string
	err   error
}

// Resolver caches positive answers for TTL, NXDOMAIN for NegTTL, and can
// serve a stale answer for up to StaleFor when the upstream is failing.
type Resolver struct {
	Next     Lookuper
	TTL      time.Duration // positive cache lifetime (e.g. 5s)
	NegTTL   time.Duration // negative cache lifetime (e.g. 2s)
	StaleFor time.Duration // serve-stale window after TTL (RFC 8767 idea)
	Now      func() time.Time

	mu       sync.Mutex
	entries  map[string]entry
	inflight map[string]*call
}

func (r *Resolver) now() time.Time {
	if r.Now != nil {
		return r.Now()
	}
	return time.Now()
}

// LookupHost returns cached addresses or resolves once per host at a time
// (concurrent callers for the same name share one upstream query).
func (r *Resolver) LookupHost(ctx context.Context, host string) ([]string, error) {
	r.mu.Lock()
	if r.entries == nil {
		r.entries = map[string]entry{}
		r.inflight = map[string]*call{}
	}
	e, ok := r.entries[host]
	if ok && r.now().Before(e.expires) {
		r.mu.Unlock()
		return append([]string(nil), e.addrs...), e.err
	}
	if c, busy := r.inflight[host]; busy {
		r.mu.Unlock()
		select {
		case <-c.done:
			return append([]string(nil), c.addrs...), c.err
		case <-ctx.Done():
			return nil, ctx.Err()
		}
	}
	c := &call{done: make(chan struct{})}
	r.inflight[host] = c
	r.mu.Unlock()

	addrs, err := r.Next.LookupHost(ctx, host)

	r.mu.Lock()
	defer r.mu.Unlock()
	delete(r.inflight, host)
	switch {
	case err == nil:
		r.entries[host] = entry{addrs: addrs, expires: r.now().Add(r.TTL)}
	case isNotFound(err):
		r.entries[host] = entry{err: err, expires: r.now().Add(r.NegTTL)}
	case ok && len(e.addrs) > 0 && r.now().Before(e.expires.Add(r.StaleFor)):
		// Upstream failed (timeout, SERVFAIL): keep serving the old answer.
		addrs, err = e.addrs, nil
	}
	c.addrs, c.err = addrs, err
	close(c.done)
	return append([]string(nil), addrs...), err
}

func isNotFound(err error) bool {
	var d *net.DNSError
	return errors.As(err, &d) && d.IsNotFound
}
go
// Command transport shows an http.Client that does not pin an old IP forever:
// it resolves through a short-TTL cache, dials every returned address, and
// drops idle keep-alive connections on a timer so the next request re-resolves.
package main

import (
	"context"
	"fmt"
	"net"
	"net/http"
	"os"
	"time"

	"academy/dns-resolution-for-developers/cache"
)

func newClient(ttl time.Duration) (*http.Client, func()) {
	resolver := &cache.Resolver{
		Next:     net.DefaultResolver,
		TTL:      ttl,
		NegTTL:   time.Second,
		StaleFor: time.Minute,
	}
	dialer := &net.Dialer{Timeout: 3 * time.Second, KeepAlive: 15 * time.Second}

	tr := &http.Transport{
		DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
			host, port, err := net.SplitHostPort(addr)
			if err != nil {
				return nil, err
			}
			ips, err := resolver.LookupHost(ctx, host)
			if err != nil {
				return nil, err
			}
			var last error
			for _, ip := range ips { // try each A/AAAA record in order
				c, err := dialer.DialContext(ctx, network, net.JoinHostPort(ip, port))
				if err == nil {
					return c, nil
				}
				last = err
			}
			return nil, last
		},
		MaxIdleConnsPerHost: 10,
		IdleConnTimeout:     ttl * 2, // idle sockets must not outlive the DNS answer for long
		ForceAttemptHTTP2:   true,
	}

	stop := make(chan struct{})
	go func() {
		t := time.NewTicker(ttl)
		defer t.Stop()
		for {
			select {
			case <-t.C:
				tr.CloseIdleConnections() // next request dials again and re-resolves
			case <-stop:
				return
			}
		}
	}()
	return &http.Client{Transport: tr, Timeout: 10 * time.Second}, func() { close(stop) }
}

func main() {
	url := "http://example.com/"
	if len(os.Args) > 1 {
		url = os.Args[1]
	}
	client, stop := newClient(5 * time.Second)
	defer stop()
	resp, err := client.Get(url)
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	defer resp.Body.Close()
	fmt.Println(resp.Status)
}
go
// Package dbpin configures database/sql so pooled connections cannot pin the
// IP address a database hostname had when the connection was first opened.
package dbpin

import (
	"database/sql"
	"time"
)

// Tune bounds connection age. After a failover the DNS name points at the new
// primary, but an open TCP connection still talks to the old IP until it is
// closed. ConnMaxLifetime guarantees every connection is eventually replaced,
// and the replacement dials again, which resolves the name again.
func Tune(db *sql.DB) {
	db.SetMaxOpenConns(20)
	db.SetMaxIdleConns(10)
	db.SetConnMaxLifetime(30 * time.Second) // replace connections at least this often
	db.SetConnMaxIdleTime(10 * time.Second) // and close idle ones sooner
}

Laravel / PHP: queue workers and Horizon keep one PDO per process, so after a failover they talk to the old IP until the socket dies. Laravel's lost-connection detector already matches Temporary failure in name resolution, getaddrinfo failed, running with the --read-only option and SQLSTATE[25006]: Read only sql transaction, and reconnects. The fix is to make workers restart (maxJobs, maxTime; "maxTime defines the number of seconds a worker should run before restarting", default 0 = never) and to add a job middleware for cases that surface as plain errors.

php
<?php

declare(strict_types=1);

namespace App\Jobs\Middleware;

use Closure;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

/**
 * Long-lived workers (queue:work, Horizon, Octane) keep one PDO connection per
 * process. After a database failover the DNS name points at the new primary,
 * but the open socket still talks to the old IP. Laravel already reconnects on
 * many "lost connection" messages; this middleware adds the cases that look
 * like normal errors and drops the stale handle so the next attempt resolves
 * the name again.
 */
final class ReconnectAfterFailover
{
    /** Message fragments that mean "you are talking to the wrong node". */
    private const STALE_NODE = [
        'read-only transaction',                     // PostgreSQL 25006 on a demoted primary
        'running with the --read-only option',       // MySQL super_read_only
        'cannot execute INSERT in a read-only',
        'Temporary failure in name resolution',
        'getaddrinfo failed',
    ];

    public function handle(object $job, Closure $next): void
    {
        try {
            $next($job);
        } catch (QueryException $e) {
            if (Str::contains($e->getMessage(), self::STALE_NODE)) {
                DB::purge();      // forget the PDO and any cached connection
                DB::reconnect();  // open a new socket: new DNS lookup, new IP
                $job->release(2); // retry soon on the new primary
                return;
            }

            throw $e;
        }
    }
}
php
<?php

// config/horizon.php (fragment). Workers restart on a schedule, so every
// process eventually opens fresh sockets and re-resolves database and API hosts.
return [
    'environments' => [
        'production' => [
            'supervisor-1' => [
                'connection' => 'redis',
                'queue' => ['default'],
                'balance' => 'auto',
                'maxProcesses' => 10,
                'maxJobs' => 1000,   // restart a worker after 1000 jobs
                'maxTime' => 3600,   // ... or after one hour, whichever comes first
                'tries' => 3,
            ],
        ],
    ],
];

// Without Horizon:  php artisan queue:work --max-jobs=1000 --max-time=3600

Slow first request (ndots) ​

Cause: search-list expansion (Search domains and ndots). Measure with tcpdump -n -i any port 53 in the pod; fix with a trailing dot, dnsConfig ndots:1 or 2, or NodeLocal DNSCache. In Go use GODEBUG=netdns=2. In Laravel: set absolute hostnames in .env (API_HOST=api.example.com. only if the client library keeps Host and TLS names right, otherwise prefer dnsConfig).

Works with dig, fails in the app ​

Walk the path: getent hosts NAME (nsswitch, /etc/hosts, search), then GODEBUG=netdns=2 for Go, then check whether the app runs in another namespace or container, uses DoH, or a static cache. Overrides when you must test one client: cURL --resolve host:443:IP; Laravel:

php
<?php

declare(strict_types=1);

namespace App\Support\Dns;

use Illuminate\Http\Client\PendingRequest;
use Illuminate\Support\Facades\Http;

/**
 * Laravel's HTTP client is Guzzle on top of cURL. cURL can be told which IP to
 * use for a host:port (CURLOPT_RESOLVE) while the URL, the Host header and the
 * TLS SNI keep the real hostname. That makes it the safest way to test a
 * new server before DNS points at it.
 */
final class HttpPinnedResolve
{
    public static function toIp(string $host, int $port, string $ip): PendingRequest
    {
        return Http::withOptions([
            'curl' => [
                // "host:port:address"; a leading + on the entry makes it time out like a normal cache entry.
                CURLOPT_RESOLVE => ["{$host}:{$port}:{$ip}"],
            ],
        ]);
    }

    /** Skip AAAA when your network has a broken IPv6 path (slow first byte, then fallback). */
    public static function ipv4Only(): PendingRequest
    {
        return Http::withOptions(['force_ip_resolve' => 'v4']);
    }

    public static function demo(): int
    {
        // Same URL, same TLS certificate check, but the TCP connection goes to the canary IP.
        $response = self::toIp('api.example.com', 443, '203.0.113.50')
            ->timeout(5)
            ->get('https://api.example.com/health');

        return $response->status();
    }
}

Email and discovery in Laravel ​

email:rfc,dns checks the domain has an MX ("It does not determine whether an individual mailbox exists"); active_url uses dns_get_record; tests call Validator::fakeDnsLookups(). SRV discovery with a short cache:

php
<?php

declare(strict_types=1);

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

/**
 * Laravel 13 validation: `email:rfc,dns` runs RFCValidation and DNSCheckValidation.
 * The DNS check confirms the domain has a valid MX record; it does NOT prove the
 * mailbox exists. Keep it out of hot paths: it is a live DNS lookup per request.
 */
final class RegisterRequest extends FormRequest
{
    /** @return array<string, list<string>> */
    public function rules(): array
    {
        return [
            'email' => ['required', 'email:rfc,dns', 'max:254'],
            // active_url checks the hostname with dns_get_record (A or AAAA).
            'website' => ['nullable', 'active_url'],
        ];
    }
}

// In tests, never depend on live DNS:
//
//     Validator::fakeDnsLookups();
//     $this->postJson('/register', ['email' => 'ann@example.test'])->assertCreated();
php
<?php

declare(strict_types=1);

namespace App\Support\Dns;

use Illuminate\Support\Facades\Cache;

/**
 * Resolve a service through SRV records and cache the answer for the shortest
 * TTL we are willing to be wrong for. PHP-FPM has no process-wide DNS cache,
 * so without this every request pays for a lookup; with a long cache you pin
 * a stale address.
 */
final class ServiceDiscovery
{
    public function __construct(private readonly DnsLookups $dns) {}

    /** @return array{host: string, port: int} */
    public function endpoint(string $service, string $domain): array
    {
        return Cache::remember("srv:{$service}.{$domain}", 10, function () use ($service, $domain): array {
            $records = $this->dns->srv($service, 'tcp', $domain);
            if ($records === []) {
                throw new \RuntimeException("No SRV record for _{$service}._tcp.{$domain}");
            }

            $top = $records[0]; // lowest priority, highest weight first
            return ['host' => $top['target'], 'port' => $top['port']];
        });
    }
}

Go resolver choices ​

text
 1  go run ./lookup -name example.com                      default: Go decides pure-Go vs cgo
 2  GODEBUG=netdns=go+1 go run ./lookup                    force pure Go, print decisions
 3  GODEBUG=netdns=cgo go run ./lookup                     force getaddrinfo (honours OS split DNS on macOS)
 4  go build -tags netgo / CGO_ENABLED=0                   static binary, pure Go only
 5  net.Resolver{PreferGo: true, Dial: customDialer}       pin a server or add a proxy; the Dial host is a literal IP
 6  lab output: "go package net: using the Go DNS resolver", "hostLookupOrder(api.lab.test) = files,dns"
 7  note: DNSError.Server still printed 127.0.0.11:53 although our Dial pointed elsewhere: it reports the resolv.conf entry

Common failures ​

SymptomLikely causeFirst checkFix
no such host / NXDOMAINName wrong, record missing, negative cache, wrong search domaindig +search NAME, dig @authoritative NAMECreate record, wait negative TTL
SERVFAILResolver cannot reach authoritative, DNSSEC failure, broken zonedig +trace, dig +cdFix delegation or zone
Timeout (5 s, 10 s)Dead nameserver, blocked UDP/TCP 53, conntrack race, REFUSED instead of NXDOMAIN on a search steptcpdump port 53, dig @serverFix server list, allow 53, NodeLocal
Works with dig, not in appnsswitch, /etc/hosts, search, cgo vs pure Go, namespacegetent hosts, GODEBUG=netdns=2Align resolver path
Stale IP after failoverTTL, JVM cache, pooled socketsCompare dig with the peer IP in ss -tnBound connection age, short TTL
Container cannot resolve peerDefault bridge, different network, --dnscat /etc/resolv.conf in containerUser-defined network, same Compose network
Container cannot resolve anythingHost DNS unreachable from container, VPN-only DNSnslookup example.com 127.0.0.11--dns, Docker daemon dns
Slow first request in podndots:5tcpdump countdnsConfig, trailing dot
EAI_AGAIN under loadResolver overload, conntrack dropsCoreDNS logs, node metricsNodeLocal DNSCache, more replicas
Only some machines failSplit DNS, VPN, per-network resolvers, DoHscutil --dns, resolvectl statusConfigure routing domains
.local slowmDNS timeoutresolvectl query, rename zoneUse another suffix
Mail rejectedMissing PTR, SPF, DKIMdig -x IP, dig TXTPublish records
Cert issuance failsCAA, challenge TXT cacheddig CAA, dig TXT _acme-challengeFix CAA, wait negative TTL

Choosing ​

SituationRecommendationExtra techniqueReason
Local multi-project dev*.test with dnsmasq or *.localhostNo /etc/hosts edits per projectWildcards, shareable
Single temporary override/etc/hosts or cURL --resolveComment with date and ownerSmallest blast radius
Compose app and databaseService names on the project networkAliases for shared namesEmbedded DNS handles it
Kubernetes internal callssvc.ns or full FQDN with trailing dotndots tuning for chatty podsFewer search queries
High-QPS clusterNodeLocal DNSCacheCoreDNS autoscalingNo conntrack on DNS path
Failover with DNSTTL 30 to 60 s + bounded connection ageHealth-checked DNS providerNeeds both layers
Apex name to a CDNALIAS/ANAME/flattening or HTTPS/SVCB aliasCheck provider TTL behaviourCNAME not allowed
Privacy on untrusted networksDoT/DoH to a trusted resolverLocal caching resolverEncryption to upstream

In architecture: from a single process to a distributed system ​

Monolith (one process, one database) ​

A Laravel app on one VM talks to mysql.internal and redis.internal, resolved by /etc/hosts or the VPC resolver. PHP-FPM resolves on every connection, so a resolver outage hurts immediately; running systemd-resolved or dnsmasq locally adds a cache. Example: DB_HOST=db.shop.internal with TTL 60; during maintenance flip the CNAME, restart workers.

Modular monolith / multiple databases ​

Several schemas, maybe several hosts: give each its own stable name (db-orders, db-billing) even when they live on one server today, so moving one later is a DNS change, not a deploy. Everyday example: reporting reads db-reports that points at a replica.

Microservices ​

Compose or Kubernetes provides discovery: payments, orders.shop.svc.cluster.local. Production example: an order service in k8s calls payments.shop (ClusterIP, balanced by kube-proxy), a third-party tax API (api.example.com, ndots:5 penalty), and a headless kafka-0.kafka-headless per-broker name. Rules: full names for cross-namespace, trailing dot or ndots tuning for external hosts, SRV or headless for client-side balancing, bounded connection age for gRPC.

Distributed data and multi-region ​

Replicas, caches and regional endpoints are chosen by name: reader.db.example (health-checked), eu.api.example (GeoDNS, see IP, DNS, GeoDNS). Failure modes: replicas promoted but clients hold old IPs; split-horizon returning private IPs to a service in the wrong VPC; resolver caches in each region holding different answers during a flip; see Replication and failover.

Scaling path ​

LoadDNS design
1x: one hostProvider resolver, hosts file for overrides
10x: several servicesLocal caching resolver per host, short TTLs on stable names
100x: Kubernetes at scaleNodeLocal DNSCache, CoreDNS replicas and autoscaling, ndots tuning, client-side resolver caches in Go and JVM with bounded TTL, own authoritative zones with health-checked records

Lab ​

Files: docs/snippets/foundations/dns-resolution-for-developers/lab/ (compose.yaml, Corefile.auth, Corefile.resolver, zones/db.lab.test, zones/db.example.test, Dockerfile.tools, ttl-experiment.sh, ndots-experiment.sh, k8s-dns-lab.yaml). Outputs below were produced on a Mac with Docker 29.8.1, CoreDNS 1.12.0 and k3s v1.31.4 (kind was not installed; the k3s container gives a real cluster and CoreDNS).

yaml
# Lab: authoritative CoreDNS (10.77.0.2) + caching CoreDNS (10.77.0.3) + a client
name: dnslab
networks:
  lab:
    ipam:
      config:
        - subnet: 10.77.0.0/24
services:
  auth:
    image: coredns/coredns:1.12.0
    command: ["-conf", "/Corefile"]
    volumes:
      - ./Corefile.auth:/Corefile:ro
      - ./zones:/zones
    networks:
      lab: { ipv4_address: 10.77.0.2 }
  resolver:
    image: coredns/coredns:1.12.0
    command: ["-conf", "/Corefile"]
    volumes:
      - ./Corefile.resolver:/Corefile:ro
    networks:
      lab: { ipv4_address: 10.77.0.3 }
    depends_on: [auth]
  client:
    build:
      context: .
      dockerfile: Dockerfile.tools
    image: dnslab-tools
    dns: [10.77.0.3]
    dns_search: [lab.test]
    networks:
      lab: { ipv4_address: 10.77.0.10 }
auth
# Authoritative server for lab.test (serves the zone file as-is)
lab.test:53 {
    file /zones/db.lab.test {
        reload 2s
    }
    log
    errors
}

# A second zone so there is an "external-looking" name to resolve
example.test:53 {
    file /zones/db.example.test
    log
}

# Everything else: a fast, definite NXDOMAIN (like CoreDNS answers for a missing cluster.local name)
.:53 {
    template ANY ANY {
        rcode NXDOMAIN
    }
}
resolver
# Caching recursive-style resolver: forwards to the authoritative server
.:53 {
    forward . 10.77.0.2
    cache 300
    log
    errors
}
test
$ORIGIN lab.test.
$TTL 60
@       IN SOA ns1.lab.test. hostmaster.lab.test. (
            2026112501 ; serial
            3600       ; refresh
            600        ; retry
            86400      ; expire
            5 )        ; negative-caching TTL (RFC 2308)
        IN NS  ns1.lab.test.
ns1     IN A   10.77.0.2
api     10 IN A     10.0.0.10
www     IN CNAME api
@       IN MX  10 mail.lab.test.
mail    IN A   10.0.0.25
@       IN TXT "v=spf1 ip4:10.0.0.25 -all"
_http._tcp IN SRV 10 60 8080 api.lab.test.
big     IN TXT "x00-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "x01-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "x02-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "x03-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "x04-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "x05-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "x06-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "x07-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "x08-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "x09-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
  1. Trace one name. dig +trace example.com A prints root NS (TTL 349162 here), com. 172800 NS, example.com. 172800 NS hera/elliott.ns.cloudflare.com, then example.com. 300 IN A 172.66.147.243 (hop sources were 198.18.x because of a TUN proxy on this laptop).
  2. TTL expectations. docker build -f Dockerfile.tools -t dnslab-tools . && docker compose up -d, then run ttl-experiment.sh in the client while editing the zone (api to 10.0.0.99, bump serial). Expected and observed: remaining TTL falls 10, 8, 6, 4, 2, the authoritative answer changes at t+8, the resolver switches at t+10.
  3. Negative cache. Query nope.lab.test (NXDOMAIN), add the record, query again every second: the resolver kept saying NXDOMAIN for about 60 s (SOA record TTL), not 5 (SOA minimum).
  4. Docker embedded DNS. docker network create dnslab, two containers with --network-alias web; nslookup web returns both IPs, cat /etc/resolv.conf shows 127.0.0.11 and ndots:0; the default bridge cannot resolve web1.
  5. Kubernetes FQDNs. kubectl apply -f k8s-dns-lab.yaml, then in the dnsutils Pod run the commands from DNS in Kubernetes; expect the ClusterIP for payments, pod IPs for payments-headless, SRV records for port http, a CNAME for ledger-db.
  6. ndots with tcpdump. docker run --network dnslab_lab --cap-add NET_RAW --dns 10.77.0.3 --dns-opt ndots:5 --dns-search shop.svc.cluster.local --dns-search svc.cluster.local --dns-search cluster.local -v $PWD/ndots-experiment.sh:/x.sh:ro dnslab-tools sh /x.sh: 8 packets (A and AAAA for four names) versus 2 with ndots:1.
  7. UDP, TCP, EDNS0. Run the four dig variants from UDP, TCP and EDNS0 against the big.lab.test TXT.

Common misconceptions ​

BeliefReality
DNS propagation takes 24 to 48 hoursCaches expire by their own TTL; only parent NS changes carry 48 h
dig equals what my app seesdig skips /etc/hosts, nsswitch and (by default) the search list
More nameservers means failover and balancingThey are tried in order after a 5 s timeout unless rotate
A CNAME works at the apexCNAME cannot coexist with SOA, NS, MX, TXT
Go caches DNSGo has no DNS cache; each dial resolves
TTL guarantees the new IP is usedPools, JVM caches and open sockets ignore it
NXDOMAIN is never cachedIt is cached by the SOA-derived negative TTL
.local is fine for internal zonesIt is reserved for mDNS
TCP 53 is optionalNeeded for large answers; block it and some lookups fail
Containers always resolve by nameOnly on user-defined networks
A name with dots is absoluteOnly a trailing dot is; ndots decides the rest
DoH hides everythingThe resolver, the IP and SNI still show it

Cheat sheet ​

TopicRemember
Pathapp, libc/Go, nsswitch files dns, hosts, stub, resolv.conf, resolver, root/TLD/authoritative
App-path toolgetent hosts NAME (dscacheutil on macOS)
DNS tooldig +short, dig +trace, dig @server, dig +search
resolv.conforder of nameservers, timeout:5, attempts:2, ndots:1, rotate
ndots:58 packets for an external name; trailing dot or ndots:1
TTLRemaining TTL counts down; staleness = slowest layer
Negative cacheSOA-derived; check the authority section
CNAMEAlone at its name; none at the apex
SRVpriority, weight, port, target
Docker127.0.0.11, user-defined networks, aliases, --dns sets upstream
Kubernetessvc.ns.svc.cluster.local, headless = pod IPs, dnsPolicy, NodeLocal
GoGODEBUG=netdns=2, net.Resolver{PreferGo, Dial}, no cache
PHPgethostbyname, dns_get_record, CURLOPT_RESOLVE, Horizon maxTime
Failovershort TTL plus bounded connection age
512 bytesTC bit, EDNS0 1232, TCP fallback

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Why can dig and curl return different addresses for the same host? Must-know ​

Answer

Answer: curl uses getaddrinfo (nsswitch, /etc/hosts, search, local caches); dig asks a DNS server directly.

2 — With ndots:5, how many queries does api.example.com cost in a pod with three search suffixes? Good to know ​

Answer

Answer: Eight packets (A and AAAA for three suffixed names and the absolute name); two with ndots:1.

3 — Why can't you put a CNAME at example.com? Important ​

Answer

Answer: A CNAME must be the only data at a name; the apex needs SOA and NS. Use ALIAS/ANAME/flattening or an HTTPS/SVCB alias.

4 — You lowered the TTL to 30 s and failed over, but the app still hits the old IP. Why? Must-know ​

Answer

Answer: Open connections, pool lifetimes or an application cache (JVM) keep the old address.

5 — What does --dns do on a user-defined Docker network? Good to know ​

Answer

Answer: It changes the upstream servers of the embedded resolver; the container still uses 127.0.0.11.

6 — How does payments resolve in Kubernetes? Must-know ​

Answer

Answer: The Pod search list appends shop.svc.cluster.local; CoreDNS answers with the ClusterIP.

7 — What does a headless Service return? Important ​

Answer

Answer: The IPs of the selected Pods (and SRV per named port), not a virtual IP.

8 — NXDOMAIN keeps appearing after you created the record. Why? Important ​

Answer

Answer: Negative caching: the earlier NXDOMAIN is cached for its SOA-derived TTL.

9 — Why must TCP 53 be allowed? Important ​

Answer

Answer: Truncated (TC) UDP answers are retried over TCP; large TXT and DNSSEC answers need it.

10 — Does Go cache DNS answers? Important ​

Answer

Answer: No; concurrent identical lookups are merged but nothing is kept.

Glossary ​

TermMeaning
Stub resolverLibrary part that sends queries to a recursive resolver
Recursive resolverServer that resolves from the root and caches
Authoritative serverHolds the zone data
getaddrinfoPortable name-to-address call
nsswitch.confSource order for lookups
/etc/hostsStatic name table
resolv.confStub resolver settings
search / ndotsSuffix list and dot threshold
TTLSeconds a record may be cached
RRsetAll records of one name and type
NXDOMAINName does not exist
NODATAName exists without that type
SERVFAILServer could not answer
Negative cachingCaching of NXDOMAIN and NODATA
CNAMEAlias to another name
ALIAS / ANAMEProvider apex alias
SRVHost, port, priority, weight
PTRReverse lookup record
CAACA authorization
HTTPS / SVCBService binding records
EDNS0Extension for larger UDP messages
TC bitTruncated response flag
DoT / DoHDNS over TLS / HTTPS
Split DNSPer-domain resolver routing
mDNSMulticast DNS for .local
CoreDNSKubernetes DNS server
Headless ServiceService without cluster IP
NodeLocal DNSCachePer-node DNS cache
ExternalNameService returning a CNAME
Embedded DNSDocker's 127.0.0.11 server

References ​

All sources were fetched (HTTP 200) and saved under the scratchpad folder sources/dns-resolution-for-developers/.

  • RFC 1034, RFC 1035, RFC 1123, RFC 2181, RFC 2308, RFC 2782, RFC 3596, RFC 6761, RFC 6762, RFC 6891, RFC 7208, RFC 6376, RFC 7489, RFC 7766, RFC 7858, RFC 8305, RFC 8375, RFC 8484, RFC 8499, RFC 8659, RFC 8767, RFC 9156, RFC 9460 (https://www.rfc-editor.org/rfc/rfcNNNN)
  • resolv.conf(5), nsswitch.conf(5), getaddrinfo(3), systemd-resolved(8), nscd(8) at https://man7.org/linux/man-pages/; macOS man 5 resolver
  • Kubernetes: DNS for Services and Pods, NodeLocal DNSCache, custom nameservers, Service (ExternalName) at https://kubernetes.io/docs/
  • Docker: networking overview, bridge driver, Compose networking at https://docs.docker.com/
  • CoreDNS plugins: https://coredns.io/plugins/kubernetes/ and /cache/
  • Go: go doc net, net/dnsclient_unix.go, net/lookup.go (https://github.com/golang/go)
  • PHP manual: gethostbyname, dns_get_record, checkdnsrr, getmxrr; Laravel 13 validation, HTTP client, queues, Horizon; Laravel LostConnectionDetector
  • libcurl CURLOPT_RESOLVE; Guzzle request options; Java net properties; PostgreSQL pg_hba.conf; MySQL host cache; dnsmasq man page; Cloudflare CNAME flattening; AWS Route 53 alias records

Built by Morteza Negahi