linux dns解析异常常因服务管理混乱导致,需先用systemctl is-active和ls -l /etc/resolv.conf确认实际生效服务(如systemd-resolved、dnsmasq或nscd),再用getent hosts和resolvectl query对比验证缓存影响,针对性执行flush-caches或restart操作,并排查/etc/hosts、nsswitch.conf及上游ttl等干扰因素。

Linux 中 DNS 解析异常,常表现为域名仍解析到旧 IP、改了 DNS 配置却没生效、或 getent hosts 和 dig 结果不一致——这往往不是“缓存没刷”,而是你没搞清谁在管解析、缓存在哪、以及工具怎么查。
先确认当前系统用的是哪个 DNS 解析服务
Linux 没有统一 DNS 缓存,不同服务各管一摊。盲目执行 resolvectl flush-caches 或 systemctl restart nscd 很可能白忙:
- 运行
systemctl is-active systemd-resolved,返回active才说明它真在跑;若为inactive或报错,别用resolvectl - 检查
/etc/resolv.conf:执行ls -l /etc/resolv.conf,若软链指向/run/systemd/resolve/stub-resolv.conf,且内容含nameserver 127.0.0.53,基本锁定是systemd-resolved - 查
dnsmasq:systemctl is-active dnsmasq,桌面环境或 NetworkManager 管理的网络常见它 - 查
nscd:systemctl is-active nscd,再看/etc/nscd.conf中是否启用了enable-cache hosts yes(默认不缓 DNS) - 若以上全 inactive,且
/etc/resolv.conf直接写了公网 DNS(如8.8.8.8),那系统根本没本地缓存,所有解析都直连上游
验证缓存是否真影响你的应用
别依赖 ping 或浏览器——它们自带缓存或走 glibc 的 networkaddress.cache(极短 TTL);也别只信 dig 或 nslookup——它们绕过系统解析器,直连 /etc/resolv.conf 里的 nameserver:
Linux 性能分析与调优专家,覆盖 CPU、内存、磁盘 I/O、网络、内核参数、编译优化、容器/K8s。适用场景:系统卡顿/高负载、内存不足/OOM/Swap 高、CPU 异常/iowait 高。
- 用
getent hosts example.com:它走 libc 的getaddrinfo(),受systemd-resolved或nscd控制,结果最贴近真实应用行为 - 用
resolvectl query example.com:看输出里是否有From cache: yes;刷新后重查,若该字段消失或响应变慢,说明缓存已清 - 用
resolvectl statistics:关注Cache current:数值是否下降,Cache hits:是否停止增长 - 对比
dig @127.0.0.53 example.com和dig @8.8.8.8 example.com:前者走 stub listener(受 resolved 缓存影响),后者直连 Google DNS(无本地缓存干扰)
针对性清除对应服务的缓存
确认服务后,按需操作,避免误操作:
-
systemd-resolved:执行
sudo resolvectl flush-caches(systemd-resolve --flush-caches已弃用,新版会报错) -
nscd:确保
/etc/nscd.conf启用了 hosts 缓存,再执行sudo systemctl restart nscd;仅刷 hosts 可用sudo nscd -i hosts -
dnsmasq:执行
sudo systemctl restart dnsmasq;若由 NetworkManager 管理,建议同步执行sudo systemctl restart NetworkManager,防止 DHCP 重推旧配置覆盖 -
无缓存服务时:检查
/etc/nsswitch.conf中hosts:行是否含dns,顺序是否合理(如files dns表示先查/etc/hosts再查 DNS)
排除其他干扰因素
缓存只是其中一环,还需排查更底层问题:
-
/etc/hosts优先级高于 DNS:若有192.168.1.100 example.com这类静态条目,getent会直接返回,删掉或注释再试 - glibc 自带短时缓存:部分版本对
getaddrinfo()结果缓存数秒,重启测试进程(如curl)可绕过 - TTL 未过期:即使本地缓存清了,上游 DNS 返回的 TTL 若还有 300 秒,
systemd-resolved仍会保留该记录,等它自然过期或强制上游刷新 - DNS 配置未生效:检查
resolvectl status输出中Global或Link下的 nameserver 是否为你期望的地址;若显示127.0.0.53但你希望直连1.1.1.1,需改 NetworkManager 设置或手动覆盖/etc/resolv.conf










