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 for | Go to |
|---|---|
| The one-minute tables: path, records, TTL | Everything in one minute |
| Why DNS bugs feel random | Why resolution matters |
Where /etc/hosts, resolv.conf and the RFCs come from | Where it comes from |
| Application to libc to nsswitch to resolver, step by step | The resolution path on a host |
/etc/hosts for local development and its limits | /etc/hosts |
nameserver, search, ndots, options | resolv.conf |
| A, AAAA, CNAME, ALIAS, MX, TXT, SRV, NS, SOA, PTR, CAA, HTTPS | Record types |
| TTL, browser, OS, resolver, JVM, Go, PHP, connection pools | TTL and caching at every layer |
| NXDOMAIN caching and "propagation" | Negative caching, Propagation myths |
Why service works in Kubernetes and the ndots:5 trap | Search domains and ndots |
VPN, corporate zones, /etc/resolver, systemd-resolved | Split DNS |
.local, .localhost, .test | mDNS and special-use names |
| 512 bytes, TC bit, EDNS0, TCP fallback | UDP, TCP and EDNS0 |
| DoT, DoH, resolver privacy | DoT and DoH |
127.0.0.11, aliases, --dns, Compose, round robin | DNS in Docker |
CoreDNS, svc.cluster.local, headless, dnsConfig, NodeLocal | DNS in Kubernetes |
| Round-robin and its limits | DNS-based load balancing |
pg_hba.conf, MySQL skip-name-resolve | Databases and DNS |
| Product by product behaviour | Per-product behaviour |
| Message bytes, error codes, glibc timing | Mechanics |
dig, resolvectl, scutil, getent | Debugging toolbox |
| Fixes in Go and Laravel | Solving the classic problems |
| Symptom to cause table | Common failures |
| Single process to multi-region | In architecture |
| Reproduce it all with Docker and k3s | Lab |
Everything in one minute
The path of one lookup. Every row is unpacked in the resolution path.
| Step | Who | Configured by | Typical surprise |
|---|---|---|---|
| 1. Application cache or pool | Your code, JVM, HTTP client, DB pool | Your code | An open connection never re-resolves |
| 2. Name-to-address call | libc getaddrinfo, or Go's own resolver | Build flags, GODEBUG=netdns | Go and curl can disagree on the same host |
| 3. Source order | nsswitch.conf hosts: line | /etc/nsswitch.conf | files before dns means /etc/hosts wins |
| 4. Static table | /etc/hosts | You | One line shadows real DNS for that name |
| 5. Stub resolver | Library inside your process | /etc/resolv.conf | search and ndots multiply queries |
| 6. Recursive resolver | ISP, 1.1.1.1, VPC resolver, CoreDNS, 127.0.0.11 | nameserver lines | It caches until the TTL ends |
| 7. Root, TLD, authoritative | The DNS tree | The zone owner | The only place a record is truly changed |
The record types.
| Type | Maps | Developer meets it when |
|---|---|---|
| A / AAAA | name to IPv4 / IPv6 | Every connection; round-robin sets |
| CNAME | name to another name | www, SaaS custom domains, ExternalName; cannot sit at the apex |
| ALIAS / ANAME | apex name to another name (provider feature) | You want a CNAME at example.com |
| MX | domain to mail servers | Email delivery, email:dns validation |
| TXT | name to free text | SPF, DKIM, DMARC, domain-ownership checks, ACME challenges |
| SRV | service name to host, port, priority, weight | Kubernetes headless services, Consul, SIP, XMPP |
| NS / SOA | zone to its servers / zone parameters | Delegation, negative-cache TTL, serials |
| PTR | IP to name (reverse DNS) | Mail reputation, pg_hba.conf hostnames, logs |
| CAA | which CAs may issue certificates | Certificate issuance failing |
| HTTPS / SVCB | service parameters, ALPN, ECH hints, alias | HTTP/3 discovery, apex aliasing without CNAME |
Where time is spent and kept.
| Layer | Who owns its lifetime | Default you should know |
|---|---|---|
| Authoritative zone | You: per-record TTL, SOA minimum | Your choice (60 to 3600 s is common) |
| Recursive resolver | The operator; honours your TTL, may clamp | CoreDNS cache 30 in k3s |
| OS or local daemon | systemd-resolved, mDNSResponder, nscd, dnsmasq | Honours the TTL |
| Application | The runtime | Go: none. JVM: networkaddress.cache.ttl. libcurl: 60 s |
| Connection pool | The pool settings | Until 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 resolvers | More lookups, more load, more exposure to resolver outages |
| A resolver outage goes unnoticed for a while | A resolver outage becomes your outage quickly |
| A change takes the whole TTL (or more) to be seen | Failover and migrations are fast |
| Stable under bursty traffic | Needs 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
- "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. - "
digshows what my application sees."digtalks to a DNS server directly and ignores/etc/hosts,nsswitch.confand the search list unless you ask. Your application usually goes throughgetaddrinfo(or Go's resolver), which does all of those.getent hosts nameis the tool that follows the application's path. - "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:
| Year | Document | What it added | Why you care |
|---|---|---|---|
| 1987 | RFC 1034, RFC 1035 | The tree, resource records, TTL, the 512-byte UDP message, the TC bit | Everything on this page starts here |
| 1989 | RFC 1123 | Requirements for resolvers (section 6.1.3.2), "MUST support UDP, and SHOULD support TCP" | Why some people think TCP is optional |
| 1997 | RFC 2181 | Clarifications: RRset TTLs, "CNAME RRs may not coexist with other data" at a name | Why a CNAME cannot sit at the apex |
| 1998 | RFC 2308 | Negative caching of NXDOMAIN and NODATA, TTL taken from the SOA | Why a missing name stays missing |
| 2000 | RFC 2782 | SRV records (priority, weight, port, target) | Service discovery without a load balancer |
| 2013 | RFC 6762 | Multicast DNS and .local | Why .local is not for your corporate zone |
| 2013 | RFC 6761 | Special-use names: localhost, test, invalid, example | Safe names for development |
| 2013 | RFC 6891 | EDNS(0): larger UDP payloads | Why 512 bytes is no longer the limit |
| 2016 | RFC 7766, RFC 7858 | DNS over TCP requirements; DNS over TLS | Privacy, large answers |
| 2018 | RFC 8484 | DNS over HTTPS | Browser-level DNS bypassing the OS |
| 2020 | RFC 8767 | Serving stale data | Resilience during resolver outages |
| 2023 | RFC 9460 | SVCB and HTTPS records | HTTP/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
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").
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.
| Component | Linux (glibc) | Alpine (musl) | macOS | Go (pure) | Go (cgo) |
|---|---|---|---|---|---|
| Entry point | getaddrinfo | getaddrinfo | getaddrinfo via mDNSResponder and scutil resolvers | net.Resolver | getaddrinfo |
Reads nsswitch.conf | Yes | No (musl has its own simple order) | No | Yes, for the hosts: order | Yes (via glibc) |
Reads /etc/hosts | Yes | Yes | Yes | Yes | Yes |
| Per-domain resolvers | Only through systemd-resolved | No | Yes (/etc/resolver, VPN) | No | Yes on macOS |
| Own DNS cache | No (daemon optional) | No | Yes (mDNSResponder) | No | Inherits 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.
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: askedReal 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 cannot | Better tool |
|---|---|---|---|
| One name to one IP on one machine | Yes | ||
Wildcard *.shop.test | No wildcards | dnsmasq address=/shop.test/127.0.0.1 | |
| Different answers per network | Static | Split DNS, /etc/resolver, systemd-resolved | |
| Test one HTTP client against a new IP | Affects the whole machine | cURL --resolve, Guzzle CURLOPT_RESOLVE | |
| Share with teammates | Local only | A real .test zone in a dev resolver | |
| Docker container | --add-host name:ip, Compose extra_hosts | The host's file is not shared | Same |
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)):
| Directive | Meaning | Default and limits |
|---|---|---|
nameserver IP | A server to query, tried in order | Up to 3 (MAXNS); if none, the local machine |
search a b c | Suffixes appended to short names | By default one entry, the local domain; only the last search line counts; unlimited since glibc 2.26, six domains and 256 characters before |
domain x | Obsolete 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:n | Seconds to wait per server | Default 5, capped to 30 |
options attempts:n | Tries before returning an error | Default 2, capped to 5 |
options rotate | Round-robin among nameservers | Off |
options single-request | Send A and AAAA sequentially | glibc sends them in parallel since 2.9 |
options no-aaaa | Suppress AAAA queries (diagnostics) | glibc 2.36 and later |
options use-vc | Use TCP | glibc 2.14 and later |
options edns0, trust-ad | Send EDNS0; trust the AD bit from the server | glibc 2.6 / 2.31 |
sortlist | Sort gethostbyname results | Up to 10 pairs |
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 triedReal 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.
| Product | Where the file comes from | Who edits it | Gotcha |
|---|---|---|---|
| Debian, Ubuntu with systemd-resolved | Symlink to the stub file | resolvectl, netplan, NetworkManager | Real servers are in resolvectl status; the file shows 127.0.0.53 |
| RHEL, Fedora | NetworkManager | nmcli, nmtui | Editing by hand is overwritten |
| macOS | Generated | System Settings, VPN clients | Not consulted; see scutil --dns |
| Alpine containers | Generated by the runtime | Docker, kubelet | musl handles search/ndots itself |
| Docker default bridge | Copy 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 network | nameserver 127.0.0.11, options ndots:0 (observed) | Docker | Names of containers resolve |
| Kubernetes Pod | Written by kubelet from dnsPolicy | dnsConfig | ndots: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.
| Type | Wire number | Example (real or lab) | Notes |
|---|---|---|---|
| A | 1 | api.lab.test. 10 IN A 10.0.0.10 | IPv4; several records form a round-robin set |
| AAAA | 28 | (RFC 3596) | IPv6; getaddrinfo asks for A and AAAA together |
| CNAME | 5 | www.github.com. 953 IN CNAME github.com. | Alias; follow-up lookup of the target |
| NS | 2 | example.com. NS hera.ns.cloudflare.com. | Delegation to the zone's servers |
| SOA | 6 | example.com. 1798 IN SOA elliott.ns.cloudflare.com. dns.cloudflare.com. 2421050422 10000 2400 604800 1800 | Serial, refresh, retry, expire, negative TTL |
| MX | 15 | 5 gmail-smtp-in.l.google.com. (lowest preference first) | Mail routing |
| TXT | 16 | "v=spf1 -all" (on example.com) | SPF, DKIM, DMARC, verification tokens |
| SRV | 33 | 5 0 993 imap.gmail.com. (for _imaps._tcp.gmail.com) | Priority, weight, port, target |
| PTR | 12 | one.one.one.one. (for 1.1.1.1) | In in-addr.arpa / ip6.arpa |
| CAA | 257 | RFC 8659 | Which CAs may issue |
| HTTPS / SVCB | 65 / 64 | RFC 9460 | Service 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.
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 recordFix: 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
| Record | Where | Example value | Purpose |
|---|---|---|---|
| MX | example.com | 10 mail.example.com. | Lower preference number is tried first |
| SPF | TXT at example.com | "v=spf1 ip4:10.0.0.25 -all" (RFC 7208) | Which IPs may send mail for the domain |
| DKIM | TXT 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 |
| DMARC | TXT at _dmarc.example.com | "v=DMARC1; p=quarantine" (RFC 7489) | Policy when SPF/DKIM fail |
| Domain ownership | TXT at the apex or a random label | A token the SaaS vendor gives you | Proves 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.
| Record | Go | PHP / Laravel |
|---|---|---|
| A / AAAA | net.LookupHost, net.LookupIP | gethostbyname (IPv4 only), dns_get_record($h, DNS_A) |
| CNAME | net.LookupCNAME | dns_get_record($h, DNS_CNAME) |
| MX | net.LookupMX | getmxrr, checkdnsrr($d, 'MX'), rule email:rfc,dns |
| TXT | net.LookupTXT | dns_get_record($h, DNS_TXT) |
| SRV | net.LookupSRV | dns_get_record($n, DNS_SRV) |
| NS | net.LookupNS | dns_get_record($h, DNS_NS) |
| PTR | net.LookupAddr | gethostbyaddr, dns_get_record on the reverse name |
| CAA, HTTPS | not 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/.
// 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)
}
}
}// 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
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
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.
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 againThat 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.
| Layer | What it caches | Who sets the lifetime | What to do |
|---|---|---|---|
| Authoritative | Nothing (it is the source) | Record TTL, SOA minimum | Lower the TTL one old-TTL before a planned change |
Recursive resolver (ISP, 1.1.1.1, VPC, CoreDNS) | Answers and NXDOMAIN | Honours TTL; may clamp min and max | Query it directly with dig @IP to see its remaining TTL |
| OS or local daemon | Answers | Honours TTL | resolvectl flush-caches, dscacheutil -flushcache (macOS), restart nscd |
| Browser | Its own host cache, plus DoH settings | Browser | chrome://net-internals/#dns |
| Application, Go | No cache. Each Dial of a hostname resolves; concurrent identical lookups are merged (singleflight) | Your code | Add a cache only if profiling shows lookup cost |
| Application, JVM | networkaddress.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.ttl | Security properties, not -D | Set networkaddress.cache.ttl=30 (a Java security property) |
| Application, PHP | No process cache; each gethostbyname or cURL connect resolves (cURL keeps a per-handle cache) | libc, libcurl | Cache 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_TIMEOUT | Zero disables it |
| Connection pool, keep-alive socket | The result of resolution, as an open TCP connection | Pool settings | ConnMaxLifetime, 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."
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.
| Where | Negative 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 |
| JVM | networkaddress.cache.negative.ttl, default 10 |
| libcurl | Since 8.16.0, failed resolves are cached for half of the cache timeout |
| Go | None |
| Browsers | Cache 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.
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| Change | What waits | Typical worst case |
|---|---|---|
| A/AAAA/CNAME value | The record's old TTL | The TTL (60 to 3600 s) |
| NS change at the registrar | The parent zone's NS TTL | Up to 48 h with 172800 |
| New record (never queried) | Negative cache if anyone asked | The negative TTL |
| Removing a record | Same as changing it | The old TTL |
| Any change, long-lived clients | Open connections and app caches | Until 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".
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 pairThe 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:
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).
| Fix | How | Trade-off |
|---|---|---|
| Trailing dot | Call api.example.com. | Code and config change; some TLS/Host-header stacks dislike it |
Lower ndots for the Pod | dnsConfig.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 calls | payments.shop.svc.cluster.local. | Verbose, immune to search order |
| Cache locally | NodeLocal DNSCache, dnsmasq, nscd, a Go cache | More components |
| Fewer suffixes | Trim search | Changes 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.
// 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.
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| Tool | How 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 |
dnsmasq | server=/corp.example/10.0.0.2 (documented form: --server=/internal.thekelleys.org.uk/192.168.1.1) |
| CoreDNS | A 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 VPC | Resolver 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.
| Name | Meaning | Use it for |
|---|---|---|
localhost, *.localhost | Loopback (many OSes and browsers resolve anything.localhost to 127.0.0.1 without a hosts entry) | Local multi-site development: shop.localhost |
*.test | Reserved for tests; never delegated | Dev zones with dnsmasq or CoreDNS |
*.local | mDNS, link-local | printer.local, macbook.local; not corporate DNS |
example.com, .example, .invalid | Documentation | Docs, tests |
*.home.arpa | Home network names | Home labs |
.dev, .app and other real TLDs | Real public TLDs | Do 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:
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)| Setting | Behaviour |
|---|---|
glibc options edns0 | Advertises a larger UDP size; use-vc forces TCP |
| Go pure resolver | Sends 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 groups | Allow UDP and TCP 53 to your resolver |
| EDNS buffer size | dig 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.
| Aspect | Plain DNS (53) | DoT (853) | DoH (443) |
|---|---|---|---|
| Encrypted | No | Yes | Yes |
| Visible to a firewall as DNS | Yes | Yes (a dedicated port) | No, looks like HTTPS |
| Who configures it | OS, resolv.conf | systemd-resolved (DNSOverTLS), Android Private DNS, stubby, unbound | Browsers (Firefox, Chrome "secure DNS"), cloudflared |
Respects /etc/hosts and split DNS | Yes | Yes, if in the OS stack | Often not: the browser asks its own resolver |
| Developer consequence | tcpdump shows names | Use the resolver's logs | A 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:
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 resolvesLine 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.
| Feature | How | Notes |
|---|---|---|
| Container name | docker run --name web1 --network dnslab | Resolves only on that network |
| Network alias | --network-alias web, Compose networks.NAME.aliases | Several containers can share an alias: DNS returns all their IPs |
| Compose service name | Service key is the DNS name on the project network | Replicas (deploy.replicas, --scale) share the service name: round-robin DNS |
--dns IP, --dns-search, --dns-option | Per container; Compose dns, dns_search, dns_opt | Docker: "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 Desktop | Lab: resolved to 192.168.65.254 |
--add-host name:ip | Writes /etc/hosts of that container | Lab: 10.1.2.3 db.local |
| Default bridge | Copy of host resolv.conf, no names | Legacy |
| Host network | Uses 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:
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)| Topic | Fact | Source or observation |
|---|---|---|
| FQDN structure | SERVICE.NAMESPACE.svc.CLUSTER_DOMAIN (default cluster.local); Pods: 10-42-0-4.shop.pod.cluster.local | Docs; lab |
dnsPolicy | ClusterFirst (default), Default (inherit node), ClusterFirstWithHostNet (needed with hostNetwork: true), None (all from dnsConfig) | Docs: ""Default" is not the default DNS policy" |
dnsConfig | nameservers (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, loadbalance | kubectl get cm coredns |
| ExternalName | A CNAME to an external name; "You may have trouble using ExternalName for ... HTTP and HTTPS" (Host header and TLS name mismatch) | Docs |
| Headless | clusterIP: None; DNS lists pod IPs; StatefulSets give each Pod a stable name | Docs |
| NodeLocal DNSCache | DaemonSet 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.18 | Docs |
| Search list limits | Kubernetes limits the search list to 32 entries and 2048 characters total | Docs (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.
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| Approach | Health checks | Respects TTL | Typical use |
|---|---|---|---|
| Plain round-robin A set | None | Resolver yes, long-lived clients no | Cheap spreading, internal tools |
| Weighted/health-checked DNS (Route 53, Cloudflare LB, NS1) | Yes, provider side | Short TTL (often 60 s or lower) | Failover between regions; see IP, DNS, GeoDNS |
| Kubernetes headless Service | Readiness removes the Pod from the set (after endpoints update) | Client dependent | gRPC client-side balancing, StatefulSets |
| SRV with priority and weight | None | Yes | Discovery with weights |
| Layer 4/7 load balancer behind one name | Yes | Name stays stable | Default 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.
-- 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;| Database | DNS on the connection path | Setting |
|---|---|---|
| PostgreSQL | Reverse then forward lookup for hostname rules; log_hostname adds a reverse lookup per connection | pg_hba.conf, log_hostname |
| MySQL / InnoDB | Reverse lookup for hostname accounts, host cache | skip_name_resolve, host_cache_size |
| SQL Server, Oracle | The client resolves the server name from its connection string; DNS is not part of authentication | Client connection string, listener |
| MongoDB | Clients resolve seed hosts; mongodb+srv:// reads SRV and TXT records | Connection string |
| Redis | Client resolves the host once per connection; Sentinel hands out IPs or hostnames (resolve-hostnames) | Client, sentinel resolve-hostnames |
| SQLite, CockroachDB | SQLite 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
| Product | Resolver used | Caches DNS? | Honours /etc/hosts | Search / ndots | Notes |
|---|---|---|---|---|---|
glibc programs (curl, PHP, Python, Node via libuv getaddrinfo) | libc stub | No (unless nscd or systemd-resolved) | Yes, via nsswitch.conf | Yes | Timeout 5 s, attempts 2 by default |
| musl (Alpine) | musl stub | No | Yes | Yes, own implementation | Behaves differently from glibc with several nameservers and truncation |
| macOS | mDNSResponder, scutil resolvers | Yes | Yes | Per resolver | /etc/resolv.conf is informational |
| Go, pure resolver | net package, reads resolv.conf | No | Yes | Yes | Preferred on Unix; GODEBUG=netdns=go |
| Go, cgo resolver | getaddrinfo | OS | Yes | OS | Used on macOS, with RES_OPTIONS, LOCALDOMAIN, unsupported nsswitch features; limited to 500 concurrent lookups |
| JVM | InetAddress over libc | Yes, 30 s class defaults or forever under a security manager | Yes | OS | Set networkaddress.cache.ttl |
| PHP-FPM / CLI | libc; dns_get_record uses the resolver library | No | gethostbyname yes | OS | Every request resolves |
| libcurl | libc or c-ares | 60 s per handle | Yes (libc) | OS | CURLOPT_RESOLVE overrides |
| Browsers | Own stack, maybe DoH | Yes | Usually | Own rules | May ignore VPN/split DNS |
| systemd-resolved | Daemon on 127.0.0.53 | Yes | Yes | Routing domains | resolvectl |
| CoreDNS (Kubernetes) | Server | cache 30 in k3s | hosts plugin | n/a | Pod ndots:5 |
| Docker embedded DNS | 127.0.0.11 | Forwards | per-container hosts | ndots:0 observed | Custom 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):
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.10Header 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
| Situation | Wire | Go (net.DNSError) | glibc | PHP |
|---|---|---|---|---|
| Name does not exist | RCODE 3 NXDOMAIN ("Name Error", RFC 1035) | IsNotFound=true, "no such host" | EAI_NONAME | gethostbyname returns the input |
| Exists, no data of that type | RCODE 0, empty answer (NODATA) | IsNotFound | EAI_NODATA or NONAME | empty array |
| Server failure | RCODE 2 SERVFAIL | IsTemporary=true | EAI_AGAIN or EAI_FAIL | false |
| Refused | RCODE 5 REFUSED | error | EAI_FAIL | false |
| No reply | none | IsTimeout=true | EAI_AGAIN after timeout x attempts | slow 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
| Question | Command | What 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 NAME | Status, remaining TTL, AUTHORITY section |
| Authoritative truth | dig +trace NAME | Root, TLD, authoritative hops and their TTLs |
| Which server answered? | dig footer SERVER: | The resolver actually used |
| Search list effect | dig +search +showsearch NAME | The expanded names tried |
| Other tools | nslookup NAME, host NAME | Same data, different defaults; nslookup applies the search list |
| Linux resolver state | resolvectl status, resolvectl query NAME, resolvectl flush-caches, resolvectl statistics | Per-link servers, routing domains, cache hits |
| macOS resolver state | scutil --dns, dscacheutil -flushcache | Per-domain resolvers, mdns flags |
| Caches | nscd -g, systemd-resolved stats | Whether a daemon holds the answer |
| Go | GODEBUG=netdns=2 ./app | using the Go DNS resolver, hostLookupOrder(NAME) = files,dns |
| Packets | tcpdump -n -i any port 53 | Query 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
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Short TTL on the record | 30 to 60 s | Simple | More lookups; does nothing for open sockets |
| Bound connection age | SetConnMaxLifetime, IdleConnTimeout, Horizon maxTime, gRPC MaxConnectionAge | Forces re-dial and re-resolve | Reconnect churn |
| Re-resolving dialer | Cache with TTL and CloseIdleConnections on a timer | Fine control | Own code |
| Reconnect on "wrong node" errors | Treat read-only and getaddrinfo errors as reconnect triggers | Self-heals | Must retry safely |
| Move the change below DNS | Virtual IP, proxy, PgBouncer/ProxySQL | No client change | Another 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.
// 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
}// 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)
}// 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
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
// 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=3600Slow 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
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
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
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
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 entryCommon failures
| Symptom | Likely cause | First check | Fix |
|---|---|---|---|
no such host / NXDOMAIN | Name wrong, record missing, negative cache, wrong search domain | dig +search NAME, dig @authoritative NAME | Create record, wait negative TTL |
| SERVFAIL | Resolver cannot reach authoritative, DNSSEC failure, broken zone | dig +trace, dig +cd | Fix delegation or zone |
| Timeout (5 s, 10 s) | Dead nameserver, blocked UDP/TCP 53, conntrack race, REFUSED instead of NXDOMAIN on a search step | tcpdump port 53, dig @server | Fix server list, allow 53, NodeLocal |
Works with dig, not in app | nsswitch, /etc/hosts, search, cgo vs pure Go, namespace | getent hosts, GODEBUG=netdns=2 | Align resolver path |
| Stale IP after failover | TTL, JVM cache, pooled sockets | Compare dig with the peer IP in ss -tn | Bound connection age, short TTL |
| Container cannot resolve peer | Default bridge, different network, --dns | cat /etc/resolv.conf in container | User-defined network, same Compose network |
| Container cannot resolve anything | Host DNS unreachable from container, VPN-only DNS | nslookup example.com 127.0.0.11 | --dns, Docker daemon dns |
| Slow first request in pod | ndots:5 | tcpdump count | dnsConfig, trailing dot |
EAI_AGAIN under load | Resolver overload, conntrack drops | CoreDNS logs, node metrics | NodeLocal DNSCache, more replicas |
| Only some machines fail | Split DNS, VPN, per-network resolvers, DoH | scutil --dns, resolvectl status | Configure routing domains |
.local slow | mDNS timeout | resolvectl query, rename zone | Use another suffix |
| Mail rejected | Missing PTR, SPF, DKIM | dig -x IP, dig TXT | Publish records |
| Cert issuance fails | CAA, challenge TXT cached | dig CAA, dig TXT _acme-challenge | Fix CAA, wait negative TTL |
Choosing
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Local multi-project dev | *.test with dnsmasq or *.localhost | No /etc/hosts edits per project | Wildcards, shareable |
| Single temporary override | /etc/hosts or cURL --resolve | Comment with date and owner | Smallest blast radius |
| Compose app and database | Service names on the project network | Aliases for shared names | Embedded DNS handles it |
| Kubernetes internal calls | svc.ns or full FQDN with trailing dot | ndots tuning for chatty pods | Fewer search queries |
| High-QPS cluster | NodeLocal DNSCache | CoreDNS autoscaling | No conntrack on DNS path |
| Failover with DNS | TTL 30 to 60 s + bounded connection age | Health-checked DNS provider | Needs both layers |
| Apex name to a CDN | ALIAS/ANAME/flattening or HTTPS/SVCB alias | Check provider TTL behaviour | CNAME not allowed |
| Privacy on untrusted networks | DoT/DoH to a trusted resolver | Local caching resolver | Encryption 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
| Load | DNS design |
|---|---|
| 1x: one host | Provider resolver, hosts file for overrides |
| 10x: several services | Local caching resolver per host, short TTLs on stable names |
| 100x: Kubernetes at scale | NodeLocal 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).
# 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 }# 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
}
}# Caching recursive-style resolver: forwards to the authoritative server
.:53 {
forward . 10.77.0.2
cache 300
log
errors
}$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"- Trace one name.
dig +trace example.com Aprints root NS (TTL 349162 here),com. 172800 NS,example.com. 172800 NS hera/elliott.ns.cloudflare.com, thenexample.com. 300 IN A 172.66.147.243(hop sources were198.18.xbecause of a TUN proxy on this laptop). - TTL expectations.
docker build -f Dockerfile.tools -t dnslab-tools . && docker compose up -d, then runttl-experiment.shin the client while editing the zone (api to10.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. - 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). - Docker embedded DNS.
docker network create dnslab, two containers with--network-alias web;nslookup webreturns both IPs,cat /etc/resolv.confshows127.0.0.11andndots:0; the default bridge cannot resolveweb1. - Kubernetes FQDNs.
kubectl apply -f k8s-dns-lab.yaml, then in thednsutilsPod run the commands from DNS in Kubernetes; expect the ClusterIP forpayments, pod IPs forpayments-headless, SRV records for porthttp, a CNAME forledger-db. - 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 withndots:1. - UDP, TCP, EDNS0. Run the four
digvariants from UDP, TCP and EDNS0 against thebig.lab.testTXT.
Common misconceptions
| Belief | Reality |
|---|---|
| DNS propagation takes 24 to 48 hours | Caches expire by their own TTL; only parent NS changes carry 48 h |
dig equals what my app sees | dig skips /etc/hosts, nsswitch and (by default) the search list |
| More nameservers means failover and balancing | They are tried in order after a 5 s timeout unless rotate |
| A CNAME works at the apex | CNAME cannot coexist with SOA, NS, MX, TXT |
| Go caches DNS | Go has no DNS cache; each dial resolves |
| TTL guarantees the new IP is used | Pools, JVM caches and open sockets ignore it |
| NXDOMAIN is never cached | It is cached by the SOA-derived negative TTL |
.local is fine for internal zones | It is reserved for mDNS |
| TCP 53 is optional | Needed for large answers; block it and some lookups fail |
| Containers always resolve by name | Only on user-defined networks |
| A name with dots is absolute | Only a trailing dot is; ndots decides the rest |
| DoH hides everything | The resolver, the IP and SNI still show it |
Cheat sheet
| Topic | Remember |
|---|---|
| Path | app, libc/Go, nsswitch files dns, hosts, stub, resolv.conf, resolver, root/TLD/authoritative |
| App-path tool | getent hosts NAME (dscacheutil on macOS) |
| DNS tool | dig +short, dig +trace, dig @server, dig +search |
| resolv.conf | order of nameservers, timeout:5, attempts:2, ndots:1, rotate |
| ndots:5 | 8 packets for an external name; trailing dot or ndots:1 |
| TTL | Remaining TTL counts down; staleness = slowest layer |
| Negative cache | SOA-derived; check the authority section |
| CNAME | Alone at its name; none at the apex |
| SRV | priority, weight, port, target |
| Docker | 127.0.0.11, user-defined networks, aliases, --dns sets upstream |
| Kubernetes | svc.ns.svc.cluster.local, headless = pod IPs, dnsPolicy, NodeLocal |
| Go | GODEBUG=netdns=2, net.Resolver{PreferGo, Dial}, no cache |
| PHP | gethostbyname, dns_get_record, CURLOPT_RESOLVE, Horizon maxTime |
| Failover | short TTL plus bounded connection age |
| 512 bytes | TC bit, EDNS0 1232, TCP fallback |
Self-check: questions & answers
- 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
| Term | Meaning |
|---|---|
| Stub resolver | Library part that sends queries to a recursive resolver |
| Recursive resolver | Server that resolves from the root and caches |
| Authoritative server | Holds the zone data |
| getaddrinfo | Portable name-to-address call |
| nsswitch.conf | Source order for lookups |
| /etc/hosts | Static name table |
| resolv.conf | Stub resolver settings |
| search / ndots | Suffix list and dot threshold |
| TTL | Seconds a record may be cached |
| RRset | All records of one name and type |
| NXDOMAIN | Name does not exist |
| NODATA | Name exists without that type |
| SERVFAIL | Server could not answer |
| Negative caching | Caching of NXDOMAIN and NODATA |
| CNAME | Alias to another name |
| ALIAS / ANAME | Provider apex alias |
| SRV | Host, port, priority, weight |
| PTR | Reverse lookup record |
| CAA | CA authorization |
| HTTPS / SVCB | Service binding records |
| EDNS0 | Extension for larger UDP messages |
| TC bit | Truncated response flag |
| DoT / DoH | DNS over TLS / HTTPS |
| Split DNS | Per-domain resolver routing |
| mDNS | Multicast DNS for .local |
| CoreDNS | Kubernetes DNS server |
| Headless Service | Service without cluster IP |
| NodeLocal DNSCache | Per-node DNS cache |
| ExternalName | Service returning a CNAME |
| Embedded DNS | Docker'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; PostgreSQLpg_hba.conf; MySQL host cache; dnsmasq man page; Cloudflare CNAME flattening; AWS Route 53 alias records