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): تبدیل یک نام به آدرس قبل از اینکه حتی یک سرور DNS پرسیده شود از چند تصمیم کوچک روی خود ماشین میگذرد (کتابخانه، nsswitch.conf، /etc/hosts، resolv.conf، کشها)، و هر حلقهٔ این زنجیره میتواند همان باشد که اشتباه است. تمرکز (Focus): حل نام روی یک میزبان، نوع رکوردهایی که برنامهنویس میبیند، TTL و کش در هر لایه، search domain و ndots، split DNS، کانتینر و Kubernetes، و رفتارهای غافلگیرکنندهٔ Go و PHP. هدف یادگیری (Learning goal): پیشبینی اینکه کدام فایل، کش یا سرور یک lookup را جواب داده، توضیح اینکه چرا dig و برنامهات با هم فرق دارند، و رفع حادثههای IP کهنه و کندیِ اولین درخواست بدون حدسزدن.
این صفحه مرجع کامل برنامهنویس برای حل نام (Name Resolution) است: فاصلهٔ connect("api.internal", 443) تا اولین SYN به یک IP. مسیر حل نام روی میزبان (برنامه، getaddrinfo در libc، nsswitch.conf، /etc/hosts، stub resolver، resolv.conf، recursive resolver، و سپس root، TLD و authoritative)، همهٔ انواع رکورد (A، AAAA، CNAME، ALIAS/ANAME، MX، TXT، SRV، NS، SOA، PTR، CAA، HTTPS/SVCB)، TTL و کش منفی، ndots، split-horizon، mDNS و .localhost، UDP و TCP و EDNS0، DoT و DoH، DNS در Docker و Kubernetes، توزیع بار با DNS، ابزارهای اشکالیابی و کد Go و Laravel/PHP اینجاست. سمت طراحی (اجرای DNS معتبر، GeoDNS، anycast) در IP, DNS, GeoDNS & TTL است و اینجا تکرار نمیشود. فصلهای همسایه: مدلهای شبکه، آدرسدهی IP، پورت، سوکت و اتصال، شبکهٔ Docker، شبکهٔ Kubernetes، VPN و تونل، TLS در عمل و راهنمای عیبیابی شبکه. عمر اتصالها در 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)
مسیر یک lookup. هر ردیف در مسیر حل نام باز میشود.
| 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 |
انواع رکورد.
| 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 |
وقت کجا صرف و نگهداری میشود.
| 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)
تقریباً هر فراخوانی سرویس با یک نام شروع میشود و مرحلهٔ نام به IP نامرئی، توزیعشده و پر از کشهایی است که خودت نصب نکردهای. وقتی درست است کسی متوجه نمیشود؛ وقتی غلط است نشانهاش بهندرت «خطای DNS» است: ۵ ثانیه مکث در اولین درخواست، سرور قدیمی که یک ساعت پس از failover هنوز ترافیک میگیرد، کانتینری که دیتابیسش را پیدا نمیکند، یا دستوری که در یک ترمینال کار میکند و در سرویس نه. موازنهٔ اصلی بین سرعت و تازگی (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) |
تشبیهی که در این صفحه تکرار میکنیم: پرسیدن شمارهٔ تلفن یک نفر. اول دفترچهٔ خودت را نگاه میکنی (/etc/hosts)، بعد یادداشتهای روی یخچال (کشها)، بعد به یک منشی کاربلد زنگ میزنی (recursive resolver) که بلد است هر کسی را پیدا کند: از دفتر ملی (root)، بعد دفتر شهر (TLD)، بعد منشی خود آن شخص (authoritative server) میپرسد. هر کدام از اینها شماره را مدتی (TTL) یادداشت میکنند و تا انقضای یادداشتشان همان شمارهٔ قدیمی را برایت میخوانند.
سه بدفهمی رایج، از همان ابتدا (Three common misunderstandings)
- «DNS یک پرسوجو از یک سرور است.» روی میزبان یک خط لوله است: کتابخانه،
nsswitch.conf،/etc/hosts، stub resolver، یک recursive resolver و فقط در صورت miss کش، root و TLD و authoritative. هر مرحله تنظیم و کش خودش را دارد. - «
digهمان چیزی را نشان میدهد که برنامهام میبیند.»digمستقیم با یک سرور DNS حرف میزند و/etc/hosts،nsswitch.confو search list را نادیده میگیرد. برنامه معمولاً ازgetaddrinfo(یا resolver خود Go) رد میشود که همهٔ آنها را اعمال میکند. ابزار مسیر برنامهgetent hosts nameاست. - «رکورد را عوض کنم، دنیا در TTL ثانیه بهروز میشود.» TTL پیشنهادی برای کشهایی است که رعایتش میکنند. مرورگر، JVM، کلاینت HTTP، connection pool و بعضی resolverها بیشتر نگه میدارند و اتصال TCP باز اصلاً دوباره resolve نمیکند.
از کجا آمده (Where it comes from)
قبل از DNS یک فایل کار را میکرد. RFC 1034 توضیح میدهد: "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" و دلیل شکست آن را میگوید: "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." سازمانها هم "had to wait for the NIC to change HOSTS.TXT to make changes visible to the Internet at large." سامانهٔ نام دامنه در RFC 1034 و RFC 1035 (نوامبر ۱۹۸۷) فایل مرکزی را با درخت واگذارشدهٔ سرورها عوض کرد؛ /etc/hosts بازماندهٔ همان طراحی قدیمی است که هنوز در بیشتر سیستمها اول خوانده میشود.
چیزهایی که بعداً به برنامهنویس میخورند همگی وصلههای روی همان طراحیاند:
| 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 |
منابع در منابع (References) آمدهاند؛ جدولهای بالا از متن RFCهایی گرفته شدهاند که هنگام نوشتن این صفحه ذخیره شدند.
کاتالوگ مفاهیم (The concept catalogue)
هر بلوک همین ترتیب را دارد: به زبان ساده، بدفهمی رایج، تعریف دقیق، خط زمانی، سناریوی واقعی، تفاوت محصولات، و روش استفاده.
مسیر حل نام روی میزبان (Resolution path) حیاتی
به زبان ساده: برنامهٔ تو DNS حرف نمیزند. از کتابخانهٔ C (یا resolver خود Go) یک آدرس میخواهد، کتابخانه تصمیم میگیرد کدام منابع را به چه ترتیبی بپرسد، و فقط بعد از آن بستههای DNS را به سروری میفرستد که در resolv.conf آمده است.
بدفهمی رایج: «برنامهام از همان سرور DNS داخل resolv.conf میپرسد.» فقط بعد از /etc/hosts، هر daemon کش محلی و قواعد search list؛ و در macOS خود /etc/resolv.conf منبع حقیقت نیست. خود فایل macOS میگوید: "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".
تعریف: یک stub resolver "cannot perform all resolution itself" و "generally depends on a recursive resolver to undertake the actual resolution function" (RFC 8499). Recursive resolver ارجاعها را از root تا authoritative دنبال و نتیجه را کش میکند. Authoritative server دادهٔ zone را دارد. getaddrinfo(3) فراخوانی قابلحمل برای گرفتن آدرس سوکت از نام است؛ کدهای خطایش: EAI_NONAME ("The node or service is not known")، EAI_AGAIN ("The name server returned a temporary failure indication. Try again later.") و 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)سناریوهای واقعی: توسعهدهنده 127.0.0.1 payments.test را به /etc/hosts اضافه میکند و سرویس Go آن را میبیند ولی dig payments.test همچنان NXDOMAIN میدهد؛ کانتینر Docker نام db را از 127.0.0.11 میگیرد و میزبان نمیتواند؛ VPN یک resolver مخصوص دامنه نصب میکند و فقط بعضی برنامهها 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 |
روش استفاده: برای دیدن آنچه برنامه میبیند در Linux از getent hosts NAME و در macOS از dscacheutil -q host -a name NAME استفاده کن؛ برای دیدن جواب سرور DNS از dig @server NAME. اگر فرق دارند، علت در مراحل ۲ تا ۵ بالاست نه در DNS.
/etc/hosts و nsswitch.conf (Static hosts) حیاتی
به زبان ساده: /etc/hosts یک فایل متنی است که نام را به IP نگاشت میکند و در سیستم عادی قبل از DNS خوانده میشود. سریعترین راه برای اشارهدادن یک نام به لپتاپت یا سرور آزمایشی است، و سریعترین راه برای فراموشکردن علت خرابی یک سال بعد.
بدفهمی رایج: «/etc/hosts سراسری است.» برای هر ماشین و هر کانتینر جداست: هر کانتینر Docker فایل تولیدی خودش را دارد، هر Pod در Kubernetes فایلی که kubelet مینویسد، و مرورگری که DNS over HTTPS دارد شاید اصلاً آن را نخواند.
تعریف: ترتیب منابع را خط hosts: در nsswitch.conf تعیین میکند. man page یک نمونه میدهد: hosts: dns [!UNAVAIL=return] files؛ پیشفرض رایج hosts: files dns است و در توزیعهای دسکتاپ گاهی mdns4_minimal [NOTFOUND=return] اول میآید. هر خط /etc/hosts یک آدرس، نام اصلی و نامهای مستعار است؛ اولین تطبیق برنده است و wildcard پشتیبانی نمیشود.
1 # /etc/nsswitch.conf # /etc/hosts
2 hosts: files mdns4_minimal [NOTFOUND=return] dns
3 127.0.0.1 localhost
4 10.0.0.25 mail.lab.test mail
5 getaddrinfo("mail.lab.test") -> files: hit -> 10.0.0.25 (DNS is never asked)
6 getaddrinfo("web.lab.test") -> files: miss -> mdns4_minimal: not .local -> dns: askedسناریوهای واقعی: اشارهدادن shop.test به 127.0.0.1 برای اپ محلی Laravel؛ آزمودن سرور جدید با نگاشت نام production به IP آن پیش از تغییر DNS؛ خط قدیمی /etc/hosts از یک مهاجرت که حالا ترافیک production را به میزبان کنارگذاشتهشده میفرستد؛ کانتینرهای CI که --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 |
روش استفاده: Docker برای میزبان host-gateway را مستند کرده: 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". در آزمایش روی همین ماشین، کانتینر روی default bridge نام host.docker.internal را به 192.168.65.254 حل کرد و --add-host db.local:10.1.2.3 در getent hosts خط 10.1.2.3 db.local داد.
resolv.conf: nameserver، search، ndots، options (Stub resolver config) حیاتی
به زبان ساده: resolv.conf به stub resolver میگوید از کدام سرورهای DNS بپرسد و نامهای کوتاه را چطور گسترش دهد. سه چهار خط است و بیشتر درد DNS در کانتینرها همینجاست.
بدفهمی رایج: «چند خط nameserver یعنی load balancing و failover.» طبق resolv.conf(5) resolver آنها را "in the order listed" میپرسد، فقط "if the query times out" سراغ بعدی میرود و "the default [timeout] is RES_TIMEOUT (currently 5)". اگر nameserver اول مرده باشد، هر lookup حدود ۵ ثانیه معطل میشود مگر options rotate باشد.
تعریف: دستورهای مهم (نقلقولها از 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 triedسناریوهای واقعی: لپتاپ روی VPN با دو nameserver که اولی VPN است و بعد از sleep در دسترس نیست (هر lookup گیر میکند)؛ کانتینر روی default bridge که resolv.conf میزبان با 127.0.0.53 را به ارث میبرد (آدرس loopback که داخل کانتینر معنای دیگری دارد)؛ Kubernetes که 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 |
روش استفاده: فایل را داخل محیطی که خراب است بخوان (docker exec، kubectl exec) نه روی لپتاپ. خروجی آزمایش: کانتینر روی شبکهٔ user-defined این را نشان داد: nameserver 127.0.0.11 و options ndots:0 و سرتیتر Docker: "Based on host file: '/etc/resolv.conf' (internal resolver)".
انواع رکورد که برنامهنویس میبیند (Record types) حیاتی
به زبان ساده: رکورد DNS یک واقعیت دربارهٔ یک نام است. نوع رکورد میگوید کدام واقعیت: آدرس IPv4، نام مستعار، سرور ایمیل، یک متن، یا پورت سرویس. هر lookup همیشه یک نوع را میپرسد.
بدفهمی رایج: «هر نام یک رکورد دارد.» هر نام به ازای هر نوع یک مجموعه (RRset) دارد؛ یک نام میتواند همزمان A، AAAA، TXT، MX و CAA داشته باشد و یک مجموعهٔ A با پنج آدرس همچنان یک RRset است.
تعریف و نوعها یکییکی. پاسخهای واقعی زیر از همین ماشین (نامهای عمومی) و از 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 و AAAA. آدرسها. برنامهها معمولاً هر دو خانواده را میگیرند و با هم مسابقه میدهند (Happy Eyeballs، RFC 8305). اگر AAAA هست ولی مسیر IPv6 خراب است، پیش از fallback به IPv4 تأخیر میبینی؛ options single-request و no-aaaa برای عیبیابی همین دستهاند و cURL و Guzzle گزینهٔ force_ip_resolve (v4/v6) دارند.
CNAME و محدودیتهایش (CNAME and its restrictions)
به زبان ساده: CNAME میگوید «این نام فقط اسم دیگری برای آن نام است». resolver دنبالش میرود و با آدرسهای نهایی جواب میدهد.
بدفهمی رایج: «میتوانم روی example.com یک CNAME به load balancer بگذارم.» نمیشود، چون CNAME باید تنها باشد: 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 تکرارش میکند. apex هر zone باید SOA و NS داشته باشد، پس CNAME آنجا نمینشیند. همین قاعده کنار CNAME هر نامی MX و TXT را هم ممنوع میکند.
1 www.shop.test. 300 IN CNAME lb-eu.provider.net. <- fine
2 lb-eu.provider.net. 60 IN A 203.0.113.7
3 shop.test. 300 IN SOA ... <- apex already has SOA and NS
4 shop.test. 300 IN CNAME lb-eu.provider.net. <- illegal: CNAME + SOA/NS/MX/TXT
5 lookup www.shop.test A -> CNAME lb-eu (TTL 300) + A 203.0.113.7 (TTL 60); the answer is cached per recordرفع: ارائهدهندهها راهحلی میفروشند، معمولاً به نام ALIAS، ANAME یا CNAME flattening: خود provider مقصد را resolve میکند و روی apex رکورد A/AAAA میدهد. Cloudflare آن را اینطور مستند کرده: "CNAME flattening ... allows you to use a CNAME record at your zone apex"؛ AWS Route 53 اسمش را alias record گذاشته ("you can create an alias record at the top node of a DNS namespace"). هزینه: TTL که میبینی TTL provider است، جواب بدون geo است مگر provider آن را بسازد، و بخشی از استاندارد DNS نیست. HTTPS/SVCB در حالت AliasMode در RFC 9460 پاسخ استاندارد برای ترافیک وب است.
MX، TXT، SPF، DKIM، DMARC و تأیید مالکیت (Mail records)
| 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) |
مقدار TXT بلندتر از ۲۵۵ بایت به چند رشتهٔ نقلقولشده در یک رکورد شکسته میشود؛ رکورد بلند پاسخ را هم از ۵۱۲ بایت بیرون میبرد (UDP، TCP و EDNS0). zone آزمایشگاه یک TXT ۶۴۰ بایتی big.lab.test دارد که فقط برای همین آزمایش است.
SRV: کشف سرویس داخل نام (Service discovery)
SRV (RFC 2782) میزبان و پورت سرویس را نام میبرد: _service._proto.name TTL IN SRV priority weight port target. کمترین priority اول امتحان میشود؛ weight ترافیک را داخل یک priority تقسیم میکند. Kubernetes برای پورتهای نامدار SRV منتشر میکند؛ آزمایشگاه 0 50 8080 10-42-0-4.payments-headless.shop.svc.cluster.local. و یک خط برای هر Pod داد. Go با net.Resolver.LookupSRV میخواند ("sorted by priority and randomized by weight within a priority") و PHP با dns_get_record($name, DNS_SRV). مرورگرها و بیشتر کلاینتهای HTTP برای HTTP از SRV استفاده نمیکنند؛ برای همین بیشتر در کشف داخلی، SIP، XMPP، LDAP و کلاینتهای دیتابیس مثل mongodb+srv:// دیده میشود.
NS و SOA (Delegation and zone parameters)
رکوردهای NS میگویند کدام سرورها authoritative هستند؛ واگذاری (delegation) در zone والد است (برای همین عوضکردن nameserver در registrar کند است: TTL مربوط به NS والد، اغلب ۱۷۲۸۰۰ ثانیه. ردیابی آزمایشگاه com. 172800 IN NS و example.com. 172800 IN NS را نشان داد). SOA شمارهٔ سریال، refresh، retry، expire و TTL کش منفی را دارد. برای برنامهنویس: سریال باید هنگام ویرایش zoneی که secondary سرو میکند زیاد شود؛ آخرین فیلد و TTL خود SOA تعیین میکند NXDOMAIN چقدر زنده بماند (کش منفی).
PTR و reverse DNS (Reverse DNS)
Reverse DNS یک IP را به نامی زیر in-addr.arpa (octetها وارونه) یا ip6.arpa نگاشت میکند. برنامهنویس وقتی به آن میخورد که سرور ایمیل بهخاطر نبود PTR ردّت میکند، وقتی لاگها hostname چاپ میکنند (یک reverse lookup برای هر اتصال کند است)، و در دیتابیسها (pg_hba.conf، host cache در MySQL؛ دیتابیسها و DNS).
CAA (Certification Authority Authorization)
CAA (RFC 8659) CAهایی را که اجازهٔ صدور برای یک نام دارند فهرست میکند: example.com. CAA 0 issue "letsencrypt.org". CAها پیش از صدور باید آن را بررسی کنند؛ CAA فراموششده دلیل شکست ناگهانی سفارش ACME پس از مهاجرت DNS است. TLS در عمل را ببین.
HTTPS و SVCB (Service binding)
RFC 9460 رکورد SVCB (نوع ۶۴) را تعریف میکند "used to locate alternative endpoints for a service" و گونهٔ HTTPS آن (نوع ۶۵). رکورد HTTPS میتواند alpn=h3، پورت، راهنمای آدرس و کلیدهای Encrypted Client Hello را اعلام کند و در AliasMode مثل CNAME ولی بدون آن محدودیت apex را alias کند. مرورگرها آن را موازی با A/AAAA میپرسند. روی شبکهٔ تمیز dig HTTPS cloudflare.com فهرست پارامترها را میدهد؛ روی این ماشین یک TUN proxy با آدرس جعلی نوع A جواب داد، که خودش درس است: middleboxها جواب DNS را عوض میکنند.
سناریوهای واقعی (رکوردها): دامنهٔ apex روی CDN (ALIAS/flattening)؛ راهاندازی یک SaaS با سه TXT و دو CNAME؛ ایمیل که بهخاطر نبود SPF/DKIM/DMARC و PTR به اسپم میرود؛ سفارش Let's Encrypt که بهخاطر CAA شکست میخورد؛ کلاینت gRPC که برای کشف از SRV استفاده میکند.
| 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 |
کد: go/lookup/main.go (همهٔ lookupها از طریق سرور انتخابی، با بررسی net.DNSError)، go/srv/main.go (کشف با SRV) و php/DnsLookups.php (wrapperهای PHP)، همه زیر 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 و کش در هر لایه (TTL and caching) حیاتی
به زبان ساده: TTL (زمان زندهماندن، Time To Live) تعداد ثانیههایی است که صاحب رکورد به دیگران اجازه میدهد آن را به خاطر بسپارند. هر کش بین تو و authoritative آن را میشمارد و وقتی به صفر رسید باید دوباره بپرسد.
بدفهمی رایج: «TTL یعنی چقدر طول میکشد تا تغییرم زنده شود.» یعنی چقدر یک نسخهٔ موجود را میشود نگه داشت. کشی که نام را هرگز ندیده نسخهٔ قدیمی ندارد؛ کشی که یک ثانیه پیش از تغییر دیده، نسخهٔ قدیمی را تا پایان TTL نگه میدارد. و TTL را فقط لایههایی رعایت میکنند که پیادهاش کردهاند: connection poolها و بعضی runtimeها نادیدهاش میگیرند.
تعریف: TTL در هر رکورد همراه پاسخ میآید؛ resolverها TTL باقیمانده را برمیگردانند، برای همین پرسوجوی تکراری شمارش معکوس نشان میدهد. RFC 2181 روشن میکند که RRset یک TTL دارد و مقدار یک عدد ۳۲ بیتی بدون علامت از ثانیههاست. بعد از تغییر صاحب zone فوراً دادهٔ تازه را میبیند، ولی کش تا انقضای نسخهٔ خودش جواب قدیمی را میدهد.
t+00s api.lab.test A 10.0.0.10 TTL 10 resolver caches it (cache 300 allows it; the record says 10)
t+02s resolver answers 10.0.0.10 remaining TTL 8
t+06s resolver answers 10.0.0.10 remaining TTL 4
t+08s operator edits the zone: api -> 10.0.0.99; authoritative now answers 10.0.0.99
t+08s resolver still answers 10.0.0.10 remaining TTL 2 <- the stale window
t+10s resolver copy expired, asks the authoritative server -> 10.0.0.99, TTL 10 againاین خط زمانی خروجی واقعی آزمایشگاه است (CoreDNS 1.12.0 هم بهعنوان authoritative و هم کشکننده، TTL رکورد ۱۰؛ آزمایشگاه را ببین): resolver مقدار ttl=2 10.0.0.10 را برگرداند در حالی که authoritative از قبل 10.0.0.99 میگفت و دو ثانیه بعد ttl=10 10.0.0.99.
سناریوهای واقعی: failover که CNAME دیتابیس را عوض میکند و برنامه ساعتها به گرهٔ قدیمی مینویسد؛ مهاجرتی که با TTL برابر ۸۶۴۰۰ برنامهریزی شده (یک روز هیچچیز برگشتپذیر نیست)؛ blue/green که برای کاربران جدید کار میکند و برای اتصالهای موجود نه.
| 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 |
روش استفاده: تازگی مؤثر را بیشینهٔ لایهها بدان نه TTLی که گذاشتهای. برای flipهای حیاتی عمر هر لایه را صریح کن: TTL ۳۰ تا ۶۰ ثانیه روی رکورد، بدون کش «برای همیشه» در JVM، و عمر اتصال کمتر از تحمل failover. الگوی کش resolver در Go در go/cache/resolver.go و کران pool در go/dbpin/pool.go است.
کش منفی (Negative caching: NXDOMAIN و NODATA) مهم
به زبان ساده: DNS «این نام وجود ندارد» و «نام هست ولی رکوردی از این نوع ندارد» را هم به خاطر میسپارد. اگر پیش از ساخت رکورد بپرسی، آن «نه» میتواند کش بماند.
بدفهمی رایج: «رکورد را همین الان ساختم، پس اولین lookup پیدایش میکند.» اگر یک دقیقه پیش چیزی روی مسیر NXDOMAIN را کش کرده باشد (health check، غلط تایپی، job در CI، prefetch مرورگر)، تا پایان TTL منفی همان «نه» را میگوید.
تعریف: RFC 2308 میگوید: "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." و کش منفی "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)خط زمانی نتیجهٔ آزمایشگاه با CoreDNS 1.12.0 بهعنوان resolver کشکننده است: TTL خود رکورد SOA برابر ۶۰ و MINIMUM آن ۵ بود؛ CoreDNS حدود ۶۰ ثانیه NXDOMAIN داد، نه ۵ ثانیهای که خواندن سختگیرانهٔ RFC 2308 ("the minimum of the SOA.MINIMUM field and SOA's TTL") میدهد. درس همین است: سروری که پاسخ منفی را میسازد تعیین میکند چه TTLی سفر کند و کشها فرق دارند. همیشه با 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 |
رفع: TTL و minimum رکورد SOA را برای zoneهایی که رکوردها پویا ظاهر میشوند کوچک نگه دار (_acme-challenge، زیردامنهٔ هر tenant)؛ رکورد را پیش از اینکه کسی بپرسد بساز؛ در CI هر اجرا نام یکتا بگیر.
افسانههای propagation (Propagation myths) مهم
به زبان ساده: «propagation در DNS» موجی که در اینترنت پخش شود نیست. هزاران کش مستقل است که نسخههایشان در زمانهای مختلف منقضی میشود.
بدفهمی رایج: «۲۴ تا ۴۸ ساعت طول میکشد.» آن ۴۸ ساعت قاعدهٔ سرانگشتیِ دوران registry برای تغییر NS در والد است (TTL رکورد NS در zone سطح بالا در ردیابی بالا ۱۷۲۸۰۰ ثانیه = ۴۸ ساعت بود). رکورد A با TTL برابر ۶۰ برای هر چیزی که TTL را رعایت کند تقریباً ظرف یک دقیقه عوض میشود.
تعریف: پس از تغییر در authoritative، کشی که نسخه دارد تا old_ttl ثانیه پس از گرفتن آن را سرو میکند، پس بدترین حالت TTL قدیمی (بهعلاوهٔ هر لایه که آن را طولانیتر کند) است. resolverهای مختلف در لحظههای مختلف گرفتهاند، پس چککنندهٔ جهانی ترکیبی از جوابها نشان میدهد نه نوار پیشرفت.
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 |
رفع: تغییرها را با ترتیب بالا برنامهریزی کن و با dig +trace (حقیقت authoritative) و dig @8.8.8.8 (آنچه آن resolver کش کرده) راستیآزمایی کن.
Search domain و ndots حیاتی
به زبان ساده: search list اجازه میدهد نام کوتاه (payments) بنویسی و resolver خودش payments.shop.svc.cluster.local را امتحان کند. ndots تعیین میکند نام «کوتاه» است (اول search list) یا «بهاندازهٔ کافی بلند که مطلق باشد» (اول همانطور که هست).
بدفهمی رایج: «نامی که نقطه دارد کاملاً مشخص (fully qualified) است و مستقیم به DNS میرود.» فقط نامی که با نقطه تمام شود (api.example.com.) مطلق است. با ndots:5 نامی مثل api.example.com دو نقطه دارد، کمتر از پنج، پس stub اول همهٔ پسوندهای search را امتحان میکند.
تعریف: 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." و: "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." و هشدار: "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 pairضبط آزمایشگاه (tcpdump داخل کانتینر کلاینت با ndots:5 و سه پسوند Kubernetes) برای یک getent hosts api.example.test هشت بسته به resolver بالادستی ثبت کرد و با ndots:1 فقط ۲. Pod واقعی در k3s (نسخهٔ v1.31.4، CoreDNS 1.12.0) این را داشت: search shop.svc.cluster.local svc.cluster.local cluster.local، nameserver 10.43.0.10، options ndots:5 و dig +search +showsearch example.com سه NXDOMAIN پیش از NOERROR نشان داد. برنامهٔ Go در go/ndots/ همین فهرست نامزدها و تعداد بسته را چاپ میکند:
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)سناریوهای واقعی: اولین فراخوانی API شخص ثالث از یک Pod ۱۰ تا ۱۰۰ میلیثانیه کندتر از لازم است؛ stubی که برای اولین پسوند بهجای NXDOMAIN سریع، REFUSED یا سکوت میگیرد در هر قدم یک timeout کامل میایستد (در یک اجرای اولیهٔ آزمایشگاه پیمایش search ۱۰٫۰۲ ثانیه طول کشید و getent با کد ۲ خارج شد، چون بالادست برای نامهای بیرون از zoneهایش جوابی نداد)؛ بعضی محیطها به محدودیتهای CoreDNS یا race در conntrack میخورند (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 |
روش استفاده: پیش از متهمکردن DNS گسترش را حساب کن؛ Candidates(name, cfg) در go/ndots/expand.go مدل تستشدهٔ این قاعده است.
// Package ndots reproduces how a stub resolver turns one name into the
// ordered list of queries it will actually send (resolv.conf search + ndots).
package ndots
import (
"strings"
)
// Config is the part of /etc/resolv.conf that decides the expansion.
type Config struct {
Search []string
Ndots int
}
// Candidates returns the fully-qualified names in the order they are tried.
// A name that ends in a dot is absolute and is never expanded.
func Candidates(name string, c Config) []string {
if strings.HasSuffix(name, ".") {
return []string{name}
}
var out []string
asIs := name + "."
withSearch := make([]string, 0, len(c.Search))
for _, s := range c.Search {
withSearch = append(withSearch, name+"."+strings.Trim(s, ".")+".")
}
if strings.Count(name, ".") >= c.Ndots {
// Enough dots: try as an absolute name first, then the search list.
out = append(out, asIs)
out = append(out, withSearch...)
} else {
// Too few dots: search list first, absolute name last.
out = append(out, withSearch...)
out = append(out, asIs)
}
return out
}
// PacketsUntil counts the DNS queries sent (A and AAAA per candidate) until
// the candidate that finally answers has been tried. -1 if it is never tried.
func PacketsUntil(name string, c Config, answer string) int {
for i, cand := range Candidates(name, c) {
if cand == answer {
return 2 * (i + 1)
}
}
return -1
}Split-horizon و Split DNS مهم
به زبان ساده: یک نام (یا یک دامنهٔ شرکت) بسته به اینکه چه کسی و از کجا میپرسد جواب متفاوت میدهد، یا بعضی دامنهها را سرور دیگری جواب میدهد. نمونه: intranet.corp.example فقط روی VPN حل میشود، و api.shop.test داخل VPC به IP خصوصی و بیرون آن به IP عمومی اشاره میکند.
بدفهمی رایج: «اگر روی ماشین من حل میشود، همهجا حل میشود.» Split DNS برای هر resolver و هر interface جداست. کلاینت VPN قواعدی نصب میکند («corp.example را به 10.0.0.2 بفرست»)؛ کانتینر، باینری Go ساختهشده بدون cgo یا فرایندی در network namespace دیگر ممکن است از آنها پیروی نکند.
تعریف: Split-horizon یعنی لایهٔ authoritative یا recursive دادهای وابسته به view برمیگرداند (view داخلی و بیرونی). Split DNS (conditional forwarding) یعنی stub یا resolver محلی پرسوجوها را بر اساس پسوند دامنه به سرورهای مختلف مسیر میدهد. systemd-resolved قاعدهٔ مسیریابی را مستند کرده: "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 با چند resolver client این کار را میکند: scutil --dns روی این ماشین کنار resolver پیشفرض، resolverهای مخصوص دامنه را فهرست کرد (domain: local با options: mdns و 254.169.in-addr.arpa) و resolver(5) توضیح میدهد فایلهای /etc/resolver به نام دامنهای که مدیریت میکنند نامگذاری میشوند.
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) |
رفع: با scutil --dns یا resolvectl status بررسی کن، بعد از دقیقاً همان محیطی که خراب است (کانتینر، pod، runtime) تست کن. هرگز فرض نکن دید یک ابزار از DNS برای ابزار دیگر هم صادق است؛ getent hosts یا lookup خود برنامه حقیقت است.
mDNS و .local و .localhost و دیگر نامهای ویژه (Special-use names) تکمیلی
به زبان ساده: بعضی نامها رزرو شدهاند. .local برای دستگاههایی است که بدون هیچ سرور DNS خودشان را روی همان بخش شبکه اعلام میکنند؛ .localhost همیشه یعنی همین ماشین؛ .test برای ساختن نام در توسعه امن است.
بدفهمی رایج: «میتوانم .local را برای zone داخلی شرکت استفاده کنم.» RFC 6762 آن را رزرو کرده: "any DNS query for a name ending with '.local.' MUST be sent to the mDNS IPv4 link-local multicast address 224.0.0.251" و مستند systemd-resolved میگوید "it is generally recommended to avoid defining '.local' in a DNS server". گذاشتن رکورد آنجا روی بعضی ماشینها lookup کند یا ناموفق میدهد (timeout در mDNS)؛ خود dig آزمایشگاه هنگام پیمایش search با cluster.local چاپ کرد "WARNING: .local is reserved for Multicast DNS".
تعریف (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" و "Name resolution APIs and libraries SHOULD recognize localhost names as special". .test برای آزمون رزرو شده و .example و .invalid هم؛ .home.arpa (RFC 8375) نام شبکهٔ خانگی است.
| 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 |
روش استفاده: برای پروژهٔ Laravel که با Herd، Valet، Sail یا Caddy سرو میشود، app.test با dnsmasq (address=/test/127.0.0.1، مستند بهصورت --address=/<domain>/<ipaddr>) یک راهاندازی برای همهٔ پروژههاست؛ app.localhost در بیشتر مرورگرها بدون تنظیم کار میکند ولی نه در هر runtime، پس با getent hosts app.localhost بررسی کن.
UDP و TCP و EDNS0 مهم
به زبان ساده: DNS معمولاً در یک بستهٔ UDP رفت و یکی برگشت میرود. اگر جواب جا نشود، سرور پرچم «بریدهشده» (truncated) میزند و کلاینت دوباره با TCP میپرسد. افزونهٔ EDNS0 اجازه میدهد کلاینت بگوید «بافر من بزرگتر است» و برای بیشتر پاسخها آن تکرار لازم نشود.
بدفهمی رایج: «DNS فقط UDP است» (پس فایروال TCP 53 را میبندد) یا «TCP اختیاری است». 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." بستهبودن TCP/53 پاسخهای بزرگ (TXT بلند، DNSSEC، A زیاد) را گاهی خراب میکند.
تعریف: RFC 1035 پیام UDP را به ۵۱۲ octet محدود میکند ("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." آزمایشگاه با پاسخ TXT به اندازهٔ ۷۳۸ بایت:
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 و حریم خصوصی resolver (Privacy) تکمیلی
به زبان ساده: DNS کلاسیک را هر کس روی مسیر میتواند بخواند. DNS over TLS (DoT) و DNS over HTTPS (DoH) همان پرسوجوها را بین تو و resolver انتخابی رمزنگاری میکنند.
بدفهمی رایج: «DoH نشان نمیدهد به کدام سایتها میروم.» پرسوجو را از شبکهٔ بین تو و resolver پنهان میکند؛ خود resolver همهٔ نامها را میبیند، IP مقصد دیده میشود و SNI (بدون ECH) نام سایت را میگوید.
تعریف: RFC 7858 DNS over TLS را مشخص میکند ("Encryption provided by TLS eliminates opportunities for eavesdropping and on-path tampering with DNS queries in the network") که قراردادی روی TCP 853 است. RFC 8484 همان را با نوع رسانهٔ application/dns-message روی HTTPS مشخص میکند. RFC 9156 (QNAME minimisation) آنچه هر authoritative در زنجیره میفهمد را کم میکند.
| 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 |
روش استفاده: وقتی «در curl کار میکند ولی در Chrome نه» (یا برعکس) بررسی کن مرورگر resolver DoH خودش را دارد یا نه؛ برای سرورها جای درست رمزنگاری بین گره و upstream است (یک unbound محلی یا forward در CoreDNS با TLS) نه داخل هر برنامه.
DNS در Docker حیاتی
به زبان ساده: روی شبکهٔ user-defined، Docker یک DNS کوچک برایت اجرا میکند. کانتینرها یکدیگر را با نام کانتینر، alias یا نام سرویس Compose پیدا میکنند؛ بقیه به DNS میزبان فوروارد میشود. روی default bridge قدیمی هیچکدام از اینها نیست.
بدفهمی رایج: «کانتینرهای یک میزبان همیشه با نام به هم میرسند.» فقط روی شبکهٔ user-defined. مستند Docker: "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." و: "Automatic service discovery only resolves custom container names, not default automatically generated names."
تعریف و آزمایشگاه. روی شبکهٔ user-defined به نام dnslab با دو کانتینر که یک 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 resolvesخط ۱۱ ظریف است: روی شبکهٔ user-defined گزینهٔ --dns جای 127.0.0.11 را نمیگیرد؛ سرورهای بالادست resolver داخلی Docker را عوض میکند. در این راهاندازی Docker برای resolver داخلی ndots:0 هم گذاشت، پس نام کوتاه همانطور که هست به سرور داخلی میرود.
| 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 |
سناریوهای واقعی: کانتینر اپ db را پیدا نمیکند چون Compose آن را روی شبکهای غیر از شبکهٔ db گذاشته (شبکهٔ Docker); docker run بدون --network از default bridge استفاده میکند و curl http://api با «could not resolve host» شکست میخورد؛ سرویسهای Laravel Sail به نام سرویسهای Compose (mysql، redis) نامگذاری شدهاند؛ دو replica پشت یک نام سرویس آدرسها را round-robin برمیگردانند ولی کلاینتی که اتصال باز نگه میدارد به یکی میچسبد.
روش استفاده: از داخل اشکالیابی کن: docker exec CONTAINER cat /etc/resolv.conf، getent hosts NAME، nslookup NAME 127.0.0.11. replicaها: docker compose up --scale api=3 و بعد getent ahosts api هر سه را فهرست میکند.
DNS در Kubernetes حیاتی
به زبان ساده: هر Pod طوری تنظیم میشود که از CoreDNS (یک Service با IP ثابت) بپرسد. CoreDNS همهٔ Serviceها را میشناسد و با cluster IP جواب میدهد؛ برای بقیه به DNS بالادست گره فوروارد میکند.
بدفهمی رایج: «Serviceها بهخاطر جادوی شبیه Docker با نام حل میشوند.» DNS معمولی است بهعلاوهٔ یک search list. payments کار میکند چون resolv.conf پاد shop.svc.cluster.local را به آن میچسباند، مثل مستند Kubernetes: "nameserver 10.32.0.10 / search NAMESPACE.svc.cluster.local svc.cluster.local cluster.local / options ndots:5" (NAMESPACE یعنی namespace همان Pod).
تعریف (از مستند DNS در Kubernetes): Serviceهای معمولی رکورد A/AAAA میگیرند "of the form my-svc.my-namespace.svc.cluster-domain.example. This resolves to the cluster IP of the Service." Serviceهای headless (بدون cluster IP) به "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." برای «named ports» رکورد SRV وجود دارد. کلاستر واقعی (k3s v1.31.4، CoreDNS 1.12.0)، از Pod در 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) |
سناریوهای واقعی: کندی اولین درخواست بهخاطر ndots:5 برای API بیرونی؛ EAI_AGAIN یا timeoutهای ۵ ثانیهای تصادفی زیر بار، که NodeLocal DNSCache با دورزدن conntrack برای بهبودشان ساخته شده؛ Pod با hostNetwork که Serviceها را حل نمیکند چون dnsPolicy: ClusterFirstWithHostNet میخواهد؛ سرویس Go که نام یک StatefulSet headless را صدا میزند و فقط یک IP میگیرد.
روش استفاده: فایل YAML آزمایشگاه lab/k8s-dns-lab.yaml (namespace، deployment، ClusterIP، headless، ExternalName و یک Pod با ابزار DNS). برای سمت شبکه (kube-proxy، ClusterIP، CNI) شبکهٔ Kubernetes را ببین.
توزیع بار با DNS و محدودیتهایش (DNS load balancing) مهم
به زبان ساده: برای یک نام چند IP برگردان و بگذار کلاینتها انتخاب کنند. ارزان و همهجا: alias در Docker، Service headless در Kubernetes، افزونهٔ loadbalance در CoreDNS، round-robin عمومی.
بدفهمی رایج: «round robin در DNS بار را یکنواخت پخش میکند و دور سرورهای مرده میزند.» resolver ترتیب را عوض میکند (یا نه)، کلاینتها بیشتر اولین آدرس را برمیدارند، مجموعه را کش میکنند، سوکت باز نگه میدارند و هیچچیز به DNS نمیگوید سروری مرده.
تعریف: DNS مجموعهای از آدرسها میدهد؛ انتخاب در کلاینت انجام میشود. نه health check هست، نه آگاهی از بار، و TTL فقط توصیه است.
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 |
روش استفاده: DNS برای هدایت درشت و کشف، load balancer واقعی برای پخش آگاه به سلامت، و کلاینتهایی که دوباره resolve میکنند (عمر اتصال کراندار، MaxConnectionAge در gRPC). dialer در Go همهٔ آدرسهای برگشتی را امتحان میکند که یک failover ابتدایی است.
دیتابیسها و DNS: hostname در pg_hba و host cache در MySQL (Databases and DNS) تکمیلی
به زبان ساده: سرور دیتابیس میتواند DNS را در دو جا به کار ببرد: برای بررسی چه کسی وصل میشود (قواعد دسترسی بر پایهٔ hostname) و برای لاگ یا تطبیق hostname کلاینت. هر دو reverse lookup به مسیر اتصال اضافه میکنند.
بدفهمی رایج: «hostname در pg_hba.conf هنگام خواندن خط resolve میشود، مثل قاعدهٔ فایروال.» PostgreSQL متفاوت عمل میکند: "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." و هشدار میدهد: "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."
تعریف: host cache در MySQL نتیجهٔ "IP-to-host name lookups" را نگه میدارد تا سرور "avoids doing a Domain Name System (DNS) lookup for each client connection"؛ "The server uses the host cache only for non-localhost TCP connections." اجرا با skip_name_resolve استفاده از hostname را خاموش میکند، یعنی الگوی host حسابها فقط IP است.
-- 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 |
رفع: در production از قواعد بر پایهٔ IP استفاده کن، یا مطمئن شو reverse DNS درست و سریع است؛ برای اتصال برنامه به نام دیتابیس Connection pooling و Replication و 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)
یک پیام DNS روی سیم (One DNS message on the wire)
ضبط واقعی از کلاینت آزمایشگاه (tcpdump -XX، پرسوجوی api.lab.test A، ۳۰ بایت 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.10پرچمهای header: QR، Opcode، AA (authoritative)، TC (truncated)، RD (recursion desired)، RA (recursion available)، RCODE. مقدار 0x0020 در پرسوجو بیت AD است که dig میزند.
کدهای پاسخ و گزارش کتابخانه (Response codes)
| 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 |
بودجهٔ زمانی یک lookup ناموفق (Time budget)
glibc: هر nameserver بهاندازهٔ timeout ثانیه فرصت دارد و فهرست attempts بار پیمایش میشود: دو سرور با پیشفرضها، ۵ ثانیه × ۲ تلاش × ۲ سرور میتواند به حدود ۲۰ ثانیه برای هر نام در هر نامزد برسد، ضرب در طول search list؛ برای همین resolver مرده شبیه برنامهٔ هنگکرده است. Go: resolver خودش timeout دارد و deadline در context را رعایت میکند؛ همیشه context با 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 |
خروجی واقعی این ماشین: dig +trace مسیر . -> com. -> example.com. -> A را رفت و برای hop ریشه Received 823 bytes from 198.18.0.2 داد. آدرسهای 198.18.x.x نشانهٔ TUN proxy است که روی این لپتاپ DNS را جعل میکند؛ روی شبکهٔ عادی این hopها IP واقعی سرورهای root و TLD را نشان میدهند. scutil --dns دو resolver روی utun4 با nameserver 198.18.0.2 و resolver شمارهٔ ۳ با domain: local, options: mdns نشان داد.
حل مسئلههای کلاسیک (Solving the classic problems)
IP کهنه بعد از failover (Stale IP)
| 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 (کش مثبت، منفی و stale با ادغام lookupهای همزمان) و go/transport/main.go (dialer که از طریق کش resolve میکند و هر آدرس را امتحان میکند؛ اتصالهای idle با تایمر بسته میشوند). تستهای کش ساعت را شبیهسازی میکنند: سه lookup یکبار به upstream میرسند، انقضا بعد از ۶ ثانیه 10.0.0.99 را برمیدارد، NXDOMAIN بهاندازهٔ NegTTL کش میشود، و upstream خراب جواب stale میدهد.
// 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: workerهای صف و Horizon یک PDO برای هر فرایند نگه میدارند، پس بعد از failover تا مرگ سوکت با IP قدیمی حرف میزنند. detector اتصالگمشدهٔ Laravel از قبل Temporary failure in name resolution، getaddrinfo failed، running with the --read-only option و SQLSTATE[25006]: Read only sql transaction را میشناسد و دوباره وصل میشود. راهحل: workerها را زمانبندیشده restart کن (maxJobs، maxTime؛ "maxTime defines the number of seconds a worker should run before restarting"، پیشفرض ۰ = هرگز) و برای حالتهایی که بهشکل خطای عادی ظاهر میشوند یک job middleware اضافه کن.
<?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=3600کندی اولین درخواست (ndots)
علت: گسترش search list (Search domain و ndots). با tcpdump -n -i any port 53 داخل pod اندازه بگیر؛ رفع با نقطهٔ انتهایی، dnsConfig با ndots:1 یا 2، یا NodeLocal DNSCache. در Go از GODEBUG=netdns=2 استفاده کن. در Laravel نام میزبان مطلق در .env بگذار (API_HOST=api.example.com. فقط اگر کتابخانهٔ کلاینت Host و نام TLS را درست نگه میدارد؛ وگرنه dnsConfig بهتر است).
با dig کار میکند ولی در برنامه نه (dig vs app)
مسیر را قدمبهقدم برو: getent hosts NAME (nsswitch، /etc/hosts، search)، بعد GODEBUG=netdns=2 برای Go، بعد ببین برنامه در namespace یا کانتینر دیگری اجرا میشود، از DoH استفاده میکند یا کش ایستا دارد. وقتی باید یک کلاینت را آزمود: 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();
}
}ایمیل و کشف سرویس در Laravel (Laravel DNS)
email:rfc,dns بررسی میکند دامنه MX دارد ("It does not determine whether an individual mailbox exists")؛ active_url از dns_get_record استفاده میکند؛ در تستها Validator::fakeDnsLookups() را صدا بزن. کشف با SRV و کش کوتاه:
<?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']];
});
}
}انتخابهای resolver در Go (Go resolver)
1 go run ./lookup -name example.com default: Go decides pure-Go vs cgo
2 GODEBUG=netdns=go+1 go run ./lookup force pure Go, print decisions
3 GODEBUG=netdns=cgo go run ./lookup force getaddrinfo (honours OS split DNS on macOS)
4 go build -tags netgo / CGO_ENABLED=0 static binary, pure Go only
5 net.Resolver{PreferGo: true, Dial: customDialer} pin a server or add a proxy; the Dial host is a literal IP
6 lab output: "go package net: using the Go DNS resolver", "hostLookupOrder(api.lab.test) = files,dns"
7 note: DNSError.Server still printed 127.0.0.11:53 although our Dial pointed elsewhere: it reports the resolv.conf entryخرابیهای رایج (Common failures)
| 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)
مونولیت (Monolith: یک فرایند، یک دیتابیس)
اپ Laravel روی یک VM با mysql.internal و redis.internal حرف میزند که با /etc/hosts یا resolver شبکهٔ خصوصی ابری حل میشوند. PHP-FPM در هر اتصال resolve میکند، پس قطع resolver فوراً آسیب میزند؛ اجرای systemd-resolved یا dnsmasq محلی کش اضافه میکند. نمونه: DB_HOST=db.shop.internal با TTL ۶۰؛ هنگام نگهداری CNAME را عوض کن و workerها را restart کن.
مونولیت ماژولار / چند دیتابیس (Modular monolith)
چند schema، شاید چند میزبان: برای هرکدام نام پایدار بگذار (db-orders، db-billing) حتی اگر امروز روی یک سرور باشند، تا جابهجایی بعدی یک تغییر DNS باشد نه deploy. نمونهٔ روزمره: گزارشگیری از db-reports میخواند که به یک replica اشاره میکند.
میکروسرویسها (Microservices)
Compose یا Kubernetes کشف را میدهد: payments، orders.shop.svc.cluster.local. نمونهٔ production: سرویس سفارش در k8s payments.shop را صدا میزند (ClusterIP، با kube-proxy متعادل)، یک API مالیاتی شخص ثالث (api.example.com، با جریمهٔ ndots:5) و نام هر broker بهصورت headless مثل kafka-0.kafka-headless. قواعد: نام کامل برای بینnamespace، نقطهٔ انتهایی یا تنظیم ndots برای میزبانهای بیرونی، SRV یا headless برای تعادل سمت کلاینت، عمر اتصال کراندار برای gRPC.
دادهی توزیعشده و چندمنطقهای (Distributed data and multi-region)
replicaها، کشها و endpointهای منطقهای با نام انتخاب میشوند: reader.db.example (با health check)، eu.api.example (GeoDNS؛ IP, DNS, GeoDNS). شکستها: replica ارتقا یافته ولی کلاینتها IP قدیمی دارند؛ split-horizon که IP خصوصی را به سرویسی در VPC اشتباه میدهد؛ کش resolver در هر منطقه که هنگام flip جواب متفاوت دارد؛ Replication و 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)
فایلها: 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). خروجیهای زیر روی یک Mac با Docker 29.8.1، CoreDNS 1.12.0 و k3s v1.31.4 تولید شدهاند (kind نصب نبود؛ کانتینر k3s یک کلاستر و 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"- ردیابی یک نام.
dig +trace example.com ANSهای root (اینجا TTL 349162)، سپسcom. 172800 NS،example.com. 172800 NS hera/elliott.ns.cloudflare.comو بعدexample.com. 300 IN A 172.66.147.243را چاپ میکند (منبع hopها198.18.xبود چون روی این لپتاپ TUN proxy هست). - انتظار TTL.
docker build -f Dockerfile.tools -t dnslab-tools . && docker compose up -d، سپسttl-experiment.shرا در client اجرا کن و همزمان zone را ویرایش کن (api به10.0.0.99و سریال را زیاد کن). مورد انتظار و مشاهدهشده: TTL باقیمانده ۱۰، ۸، ۶، ۴، ۲ میشود، جواب authoritative در t+8 عوض میشود و resolver در t+10. - کش منفی.
nope.lab.testرا بپرس (NXDOMAIN)، رکورد را اضافه کن و هر ثانیه دوباره بپرس: resolver حدود ۶۰ ثانیه (TTL رکورد SOA) NXDOMAIN گفت، نه ۵ (minimum در SOA). - DNS داخلی Docker.
docker network create dnslab، دو کانتینر با--network-alias web؛nslookup webهر دو IP را میدهد،cat /etc/resolv.confمقدار127.0.0.11وndots:0را نشان میدهد؛ default bridge نمیتواندweb1را حل کند. - FQDNهای Kubernetes.
kubectl apply -f k8s-dns-lab.yaml، سپس در Pod به نامdnsutilsدستورهای DNS در Kubernetes را بزن؛ انتظار: ClusterIP برایpayments، IP پادها برایpayments-headless، رکورد SRV برای پورتhttpو CNAME برایledger-db. - ndots با 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: هشت بسته (A و AAAA برای چهار نام) در برابر ۲ باndots:1. - UDP، TCP، EDNS0. چهار نوع
digاز UDP و TCP و EDNS0 را روی TXT به نامbig.lab.testاجرا کن.
بدفهمیهای رایج (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 |
خودآزمایی: پرسش و پاسخ
- حیاتی تقریباً در هر مصاحبه پرسیده میشود
- مهم پرتکرار؛ در سطح senior انتظار میرود
- تکمیلی عمق بیشتر؛ تمایز ایجاد میکند
۱ — چرا dig و curl میتوانند برای یک میزبان آدرسهای متفاوت بدهند؟ حیاتی
پاسخ
پاسخ: curl از getaddrinfo استفاده میکند (nsswitch، /etc/hosts، search، کشهای محلی)؛ dig مستقیم از یک سرور DNS میپرسد.
۲ — با ndots:5 نام api.example.com در Podی با سه پسوند search چند پرسوجو خرج دارد؟ تکمیلی
پاسخ
پاسخ: هشت بسته (A و AAAA برای سه نام پسوندی و نام مطلق)؛ با ndots:1 دو بسته.
۳ — چرا نمیشود روی example.com CNAME گذاشت؟ مهم
پاسخ
پاسخ: CNAME باید تنها دادهٔ آن نام باشد؛ apex به SOA و NS نیاز دارد. از ALIAS/ANAME/flattening یا alias در HTTPS/SVCB استفاده کن.
۴ — TTL را به ۳۰ ثانیه رساندی و failover کردی ولی برنامه هنوز به IP قدیمی میرود. چرا؟ حیاتی
پاسخ
پاسخ: اتصالهای باز، عمر pool یا کش برنامه (JVM) آدرس قدیمی را نگه میدارند.
۵ — --dns روی شبکهٔ user-defined در Docker چه میکند؟ تکمیلی
پاسخ
پاسخ: سرورهای بالادست resolver داخلی را عوض میکند؛ کانتینر همچنان از 127.0.0.11 میپرسد.
۶ — payments در Kubernetes چطور حل میشود؟ حیاتی
پاسخ
پاسخ: search list پاد shop.svc.cluster.local را اضافه میکند و CoreDNS با ClusterIP جواب میدهد.
۷ — Service از نوع headless چه برمیگرداند؟ مهم
پاسخ
پاسخ: IP پادهای انتخابشده (و SRV برای هر پورت نامدار)، نه IP مجازی.
۸ — بعد از ساخت رکورد هنوز NXDOMAIN میگیری. چرا؟ مهم
پاسخ
پاسخ: کش منفی: NXDOMAIN قبلی تا TTL برگرفته از SOA کش میماند.
۹ — چرا TCP 53 باید باز باشد؟ مهم
پاسخ
پاسخ: پاسخ UDP بریدهشده (TC) با TCP تکرار میشود؛ TXT بلند و DNSSEC به آن نیاز دارند.
۱۰ — آیا Go پاسخ DNS را کش میکند؟ مهم
پاسخ
پاسخ: نه؛ lookupهای همزمان یکسان ادغام میشوند ولی چیزی نگه داشته نمیشود.
واژهنامه (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)
همهٔ منابع واکشی شدند (HTTP 200) و متنشان در پوشهٔ scratchpad زیر 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