Skip to content

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

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

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

همه‌چیز در یک دقیقه (Everything in one minute) ​

مسیر یک lookup. هر ردیف در مسیر حل نام باز می‌شود.

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

انواع رکورد.

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

وقت کجا صرف و نگهداری می‌شود.

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

چرا حل نام برای برنامه‌نویس مهم است (Why) ​

تقریباً هر فراخوانی سرویس با یک نام شروع می‌شود و مرحلهٔ نام به 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 resolversMore lookups, more load, more exposure to resolver outages
A resolver outage goes unnoticed for a whileA resolver outage becomes your outage quickly
A change takes the whole TTL (or more) to be seenFailover and migrations are fast
Stable under bursty trafficNeeds a local caching layer (NodeLocal, dnsmasq, systemd-resolved)

تشبیهی که در این صفحه تکرار می‌کنیم: پرسیدن شمارهٔ تلفن یک نفر. اول دفترچهٔ خودت را نگاه می‌کنی (/etc/hosts)، بعد یادداشت‌های روی یخچال (کش‌ها)، بعد به یک منشی کاربلد زنگ می‌زنی (recursive resolver) که بلد است هر کسی را پیدا کند: از دفتر ملی (root)، بعد دفتر شهر (TLD)، بعد منشی خود آن شخص (authoritative server) می‌پرسد. هر کدام از این‌ها شماره را مدتی (TTL) یادداشت می‌کنند و تا انقضای یادداشت‌شان همان شمارهٔ قدیمی را برایت می‌خوانند.

سه بدفهمی رایج، از همان ابتدا (Three common misunderstandings) ​

  1. «DNS یک پرس‌وجو از یک سرور است.» روی میزبان یک خط لوله است: کتابخانه، nsswitch.conf، /etc/hosts، stub resolver، یک recursive resolver و فقط در صورت miss کش، root و TLD و authoritative. هر مرحله تنظیم و کش خودش را دارد.
  2. «dig همان چیزی را نشان می‌دهد که برنامه‌ام می‌بیند.» dig مستقیم با یک سرور DNS حرف می‌زند و /etc/hosts، nsswitch.conf و search list را نادیده می‌گیرد. برنامه معمولاً از getaddrinfo (یا resolver خود Go) رد می‌شود که همهٔ آن‌ها را اعمال می‌کند. ابزار مسیر برنامه getent hosts name است.
  3. «رکورد را عوض کنم، دنیا در 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 بازماندهٔ همان طراحی قدیمی است که هنوز در بیشتر سیستم‌ها اول خوانده می‌شود.

چیزهایی که بعداً به برنامه‌نویس می‌خورند همگی وصله‌های روی همان طراحی‌اند:

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

منابع در منابع (References) آمده‌اند؛ جدول‌های بالا از متن RFCهایی گرفته شده‌اند که هنگام نوشتن این صفحه ذخیره شدند.

کاتالوگ مفاهیم (The concept catalogue) ​

هر بلوک همین ترتیب را دارد: به زبان ساده، بدفهمی رایج، تعریف دقیق، خط زمانی، سناریوی واقعی، تفاوت محصولات، و روش استفاده.

مسیر حل نام روی میزبان (Resolution path) حیاتی ​

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

به زبان ساده: برنامهٔ تو 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").

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

سناریوهای واقعی: توسعه‌دهنده 127.0.0.1 payments.test را به /etc/hosts اضافه می‌کند و سرویس Go آن را می‌بیند ولی dig payments.test همچنان NXDOMAIN می‌دهد؛ کانتینر Docker نام db را از 127.0.0.11 می‌گیرد و میزبان نمی‌تواند؛ VPN یک resolver مخصوص دامنه نصب می‌کند و فقط بعضی برنامه‌ها zone داخلی را می‌بینند.

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

روش استفاده: برای دیدن آنچه برنامه می‌بیند در 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 پشتیبانی نمی‌شود.

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

سناریوهای واقعی: اشاره‌دادن shop.test به 127.0.0.1 برای اپ محلی Laravel؛ آزمودن سرور جدید با نگاشت نام production به IP آن پیش از تغییر DNS؛ خط قدیمی /etc/hosts از یک مهاجرت که حالا ترافیک production را به میزبان کنار‌گذاشته‌شده می‌فرستد؛ کانتینرهای CI که --add-host می‌خواهند.

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

روش استفاده: 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)):

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

سناریوهای واقعی: لپ‌تاپ روی VPN با دو nameserver که اولی VPN است و بعد از sleep در دسترس نیست (هر lookup گیر می‌کند)؛ کانتینر روی default bridge که resolv.conf میزبان با 127.0.0.53 را به ارث می‌برد (آدرس loopback که داخل کانتینر معنای دیگری دارد)؛ Kubernetes که ndots:5 تزریق می‌کند.

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

روش استفاده: فایل را داخل محیطی که خراب است بخوان (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 گرفته شده‌اند.

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

A و 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 را هم ممنوع می‌کند.

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

رفع: ارائه‌دهنده‌ها راه‌حلی می‌فروشند، معمولاً به نام 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) ​

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

مقدار 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 استفاده می‌کند.

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

کد: go/lookup/main.go (همهٔ lookupها از طریق سرور انتخابی، با بررسی net.DNSError)، go/srv/main.go (کشف با SRV) و php/DnsLookups.php (wrapperهای PHP)، همه زیر docs/snippets/foundations/dns-resolution-for-developers/.

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

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

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

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

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

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

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

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

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

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

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

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

declare(strict_types=1);

namespace App\Support\Dns;

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

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

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

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

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

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

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

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

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

        return $hosts;
    }

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

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

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

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

        return false;
    }
}

TTL و کش در هر لایه (TTL and caching) حیاتی ​

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

به زبان ساده: TTL (زمان زنده‌ماندن، Time To Live) تعداد ثانیه‌هایی است که صاحب رکورد به دیگران اجازه می‌دهد آن را به خاطر بسپارند. هر کش بین تو و authoritative آن را می‌شمارد و وقتی به صفر رسید باید دوباره بپرسد.

بدفهمی رایج: «TTL یعنی چقدر طول می‌کشد تا تغییرم زنده شود.» یعنی چقدر یک نسخهٔ موجود را می‌شود نگه داشت. کشی که نام را هرگز ندیده نسخهٔ قدیمی ندارد؛ کشی که یک ثانیه پیش از تغییر دیده، نسخهٔ قدیمی را تا پایان TTL نگه می‌دارد. و TTL را فقط لایه‌هایی رعایت می‌کنند که پیاده‌اش کرده‌اند: connection poolها و بعضی runtimeها نادیده‌اش می‌گیرند.

تعریف: TTL در هر رکورد همراه پاسخ می‌آید؛ resolverها TTL باقی‌مانده را برمی‌گردانند، برای همین پرس‌وجوی تکراری شمارش معکوس نشان می‌دهد. RFC 2181 روشن می‌کند که RRset یک TTL دارد و مقدار یک عدد ۳۲ بیتی بدون علامت از ثانیه‌هاست. بعد از تغییر صاحب zone فوراً دادهٔ تازه را می‌بیند، ولی کش تا انقضای نسخهٔ خودش جواب قدیمی را می‌دهد.

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

این خط زمانی خروجی واقعی آزمایشگاه است (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 که برای کاربران جدید کار می‌کند و برای اتصال‌های موجود نه.

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

روش استفاده: تازگی مؤثر را بیشینهٔ لایه‌ها بدان نه 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."

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

خط زمانی نتیجهٔ آزمایشگاه با 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 بررسی کن.

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

رفع: 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های مختلف در لحظه‌های مختلف گرفته‌اند، پس چک‌کنندهٔ جهانی ترکیبی از جواب‌ها نشان می‌دهد نه نوار پیشرفت.

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

رفع: تغییرها را با ترتیب بالا برنامه‌ریزی کن و با 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".

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

ضبط آزمایشگاه (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/ همین فهرست نامزدها و تعداد بسته را چاپ می‌کند:

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

سناریوهای واقعی: اولین فراخوانی API شخص ثالث از یک Pod ۱۰ تا ۱۰۰ میلی‌ثانیه کندتر از لازم است؛ stubی که برای اولین پسوند به‌جای NXDOMAIN سریع، REFUSED یا سکوت می‌گیرد در هر قدم یک timeout کامل می‌ایستد (در یک اجرای اولیهٔ آزمایشگاه پیمایش search ‏۱۰٫۰۲ ثانیه طول کشید و getent با کد ۲ خارج شد، چون بالادست برای نام‌های بیرون از zoneهایش جوابی نداد)؛ بعضی محیط‌ها به محدودیت‌های CoreDNS یا race در conntrack می‌خورند (Kubernetes).

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

روش استفاده: پیش از متهم‌کردن DNS گسترش را حساب کن؛ Candidates(name, cfg) در go/ndots/expand.go مدل تست‌شدهٔ این قاعده است.

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 به نام دامنه‌ای که مدیریت می‌کنند نام‌گذاری می‌شوند.

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

رفع: با 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) نام شبکهٔ خانگی است.

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

روش استفاده: برای پروژهٔ 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 به اندازهٔ ۷۳۸ بایت:

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

DoT و DoH و حریم خصوصی 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 در زنجیره می‌فهمد را کم می‌کند.

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

روش استفاده: وقتی «در 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 مشترک دارند:

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

خط ۱۱ ظریف است: روی شبکهٔ user-defined گزینهٔ --dns جای 127.0.0.11 را نمی‌گیرد؛ سرورهای بالادست resolver داخلی Docker را عوض می‌کند. در این راه‌اندازی Docker برای resolver داخلی ndots:0 هم گذاشت، پس نام کوتاه همان‌طور که هست به سرور داخلی می‌رود.

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

سناریوهای واقعی: کانتینر اپ 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:

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

سناریوهای واقعی: کندی اولین درخواست به‌خاطر 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 فقط توصیه است.

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

روش استفاده: 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 است.

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

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

رفع: در production از قواعد بر پایهٔ IP استفاده کن، یا مطمئن شو reverse DNS درست و سریع است؛ برای اتصال برنامه به نام دیتابیس Connection pooling و Replication و failover را ببین.

رفتار به تفکیک محصول (Per-product behaviour) ​

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

سازوکار (Mechanics) ​

یک پیام DNS روی سیم (One DNS message on the wire) ​

ضبط واقعی از کلاینت آزمایشگاه (tcpdump -XX، پرس‌وجوی api.lab.test A، ۳۰ بایت DNS):

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

پرچم‌های header: QR، Opcode، AA (authoritative)، TC (truncated)، RD (recursion desired)، RA (recursion available)، RCODE. مقدار 0x0020 در پرس‌وجو بیت AD است که dig می‌زند.

کدهای پاسخ و گزارش کتابخانه (Response codes) ​

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

بودجهٔ زمانی یک lookup ناموفق (Time budget) ​

glibc: هر nameserver به‌اندازهٔ timeout ثانیه فرصت دارد و فهرست attempts بار پیمایش می‌شود: دو سرور با پیش‌فرض‌ها، ۵ ثانیه × ۲ تلاش × ۲ سرور می‌تواند به حدود ۲۰ ثانیه برای هر نام در هر نامزد برسد، ضرب در طول search list؛ برای همین resolver مرده شبیه برنامهٔ هنگ‌کرده است. Go: resolver خودش timeout دارد و deadline در context را رعایت می‌کند؛ همیشه context با deadline بده.

جعبه‌ابزار اشکال‌یابی (Debugging toolbox) ​

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

خروجی واقعی این ماشین: 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) ​

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

Go: go/dbpin/pool.go (SetConnMaxLifetime(30s))، go/cache/resolver.go (کش مثبت، منفی و stale با ادغام lookupهای هم‌زمان) و go/transport/main.go (dialer که از طریق کش resolve می‌کند و هر آدرس را امتحان می‌کند؛ اتصال‌های idle با تایمر بسته می‌شوند). تست‌های کش ساعت را شبیه‌سازی می‌کنند: سه lookup یک‌بار به upstream می‌رسند، انقضا بعد از ۶ ثانیه 10.0.0.99 را برمی‌دارد، NXDOMAIN به‌اندازهٔ NegTTL کش می‌شود، و upstream خراب جواب stale می‌دهد.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

import (
	"database/sql"
	"time"
)

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

Laravel / PHP: 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
<?php

declare(strict_types=1);

namespace App\Jobs\Middleware;

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

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

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

            throw $e;
        }
    }
}
php
<?php

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

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

کندی اولین درخواست (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
<?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
<?php

declare(strict_types=1);

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

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

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

declare(strict_types=1);

namespace App\Support\Dns;

use Illuminate\Support\Facades\Cache;

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

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

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

انتخاب‌های resolver در Go (Go resolver) ​

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

خرابی‌های رایج (Common failures) ​

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

انتخاب (Choosing) ​

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

در معماری: از یک فرایند تا سیستم توزیع‌شده (In architecture) ​

مونولیت (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) ​

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

آزمایشگاه (Lab) ​

فایل‌ها: 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 واقعی می‌دهد).

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

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

# Everything else: a fast, definite NXDOMAIN (like CoreDNS answers for a missing cluster.local name)
.:53 {
    template ANY ANY {
        rcode NXDOMAIN
    }
}
resolver
# Caching recursive-style resolver: forwards to the authoritative server
.:53 {
    forward . 10.77.0.2
    cache 300
    log
    errors
}
test
$ORIGIN lab.test.
$TTL 60
@       IN SOA ns1.lab.test. hostmaster.lab.test. (
            2026112501 ; serial
            3600       ; refresh
            600        ; retry
            86400      ; expire
            5 )        ; negative-caching TTL (RFC 2308)
        IN NS  ns1.lab.test.
ns1     IN A   10.77.0.2
api     10 IN A     10.0.0.10
www     IN CNAME api
@       IN MX  10 mail.lab.test.
mail    IN A   10.0.0.25
@       IN TXT "v=spf1 ip4:10.0.0.25 -all"
_http._tcp IN SRV 10 60 8080 api.lab.test.
big     IN TXT "x00-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "x01-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "x02-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "x03-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "x04-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "x05-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "x06-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "x07-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "x08-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "x09-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
  1. ردیابی یک نام. dig +trace example.com A NSهای 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 هست).
  2. انتظار 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.
  3. کش منفی. nope.lab.test را بپرس (NXDOMAIN)، رکورد را اضافه کن و هر ثانیه دوباره بپرس: resolver حدود ۶۰ ثانیه (TTL رکورد SOA) NXDOMAIN گفت، نه ۵ (minimum در SOA).
  4. 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 را حل کند.
  5. FQDNهای Kubernetes. kubectl apply -f k8s-dns-lab.yaml، سپس در Pod به نام dnsutils دستورهای DNS در Kubernetes را بزن؛ انتظار: ClusterIP برای payments، IP پادها برای payments-headless، رکورد SRV برای پورت http و CNAME برای ledger-db.
  6. 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.
  7. UDP، TCP، EDNS0. چهار نوع dig از UDP و TCP و EDNS0 را روی TXT به نام big.lab.test اجرا کن.

بدفهمی‌های رایج (Common misconceptions) ​

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

یادسپار (Cheat sheet) ​

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

خودآزمایی: پرسش و پاسخ ​

نمایش:
  • حیاتی تقریباً در هر مصاحبه پرسیده می‌شود
  • مهم پرتکرار؛ در سطح 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) ​

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

منابع (References) ​

همهٔ منابع واکشی شدند (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; PostgreSQL pg_hba.conf; MySQL host cache; dnsmasq man page; Cloudflare CNAME flattening; AWS Route 53 alias records

ساخته‌شده توسط Morteza Negahi