nscd dns缓存未生效的根本原因是其不自动接管解析,必须同时满足:/etc/nscd.conf中enable-cache hosts yes且参数合理、/etc/nsswitch.conf的hosts行含nscd或files前置、无systemd-resolved等服务冲突。

nscd 服务没生效?先确认它是否真的在管 DNS 解析
Linux 本身不自带 DNS 缓存,nscd 只是“可能”参与解析,但不会自动接管。它的实际作用取决于两个文件的协同:/etc/nscd.conf 和 /etc/nsswitch.conf。常见现象是 systemctl status nscd 显示 active,但 dig example.com 每次都发新请求、nslookup 响应时间不变——说明缓存根本没被调用。
必须同时满足以下条件,nscd 才会缓存 hosts 解析(即域名 → IP):
-
/etc/nscd.conf中enable-cache hosts yes已开启,且positive-time-to-live hosts设为合理值(如3600) -
/etc/nsswitch.conf的hosts:行包含nscd或依赖其前置项(典型写法是hosts: files nscd dns或hosts: files dns—— 注意:仅当files在前且系统调用gethostbyname()类接口时,nscd才有机会介入;dns直连 resolver,绕过nscd) - 没有其他服务冲突,比如
systemd-resolved把/etc/resolv.conf指向127.0.0.53,而nscd完全不处理该路径下的查询
修改 /etc/nscd.conf 的关键参数不能只开开关
光把 enable-cache hosts yes 写进去远远不够。缓存效果受多个参数联动影响,尤其容易忽略的是 check-files hosts yes 和 shared hosts yes:
-
check-files hosts yes:让nscd监控/etc/hosts变更。关掉它,改了/etc/hosts也不会自动失效缓存 -
shared hosts yes:允许客户端直接读内存缓存,避免 IPC 开销。生产环境建议开启 -
max-db-size hosts 33554432(32MB):默认值太小,高并发场景下缓存迅速挤满并频繁淘汰,建议设为至少 32MB -
positive-time-to-live hosts 3600和negative-time-to-live hosts 20:前者决定成功解析缓存多久,后者决定“查无此域”这类失败结果也缓存 20 秒——避免反复重试无效域名
启动后怎么验证 nscd 真正在缓存?别信 systemctl status
systemctl status nscd 只告诉你进程活着,不等于缓存命中。真正有效的验证方式是结合 nscd -g 统计和外部工具比对:
- 执行
nscd -g,重点看hosts缓存块下的cache hits和cache misses—— 连续两次ping example.com后,hits 应该增加 - 用
dig +short example.com @8.8.8.8获取权威答案,再用dig +short example.com(不指定服务器)对比响应时间与结果一致性;若后者明显更快且结果相同,说明缓存生效 - 注意避开应用层干扰:浏览器、curl 默认走自己的 DNS 缓存,测试务必用
dig或getent hosts example.com
和其他 DNS 服务共存时,nscd 很可能被绕过
现代 Linux 发行版(Ubuntu 20.04+、Fedora 33+、Debian 11+)默认启用 systemd-resolved,它接管 /etc/resolv.conf 并监听 127.0.0.53。此时即使 nscd 正常运行,大多数命令(包括 ping、curl)走的是 resolved 路径,完全不经过 nscd。
若坚持用 nscd,必须切断 resolved 干扰:
- 停用
systemd-resolved:sudo systemctl stop systemd-resolved && sudo systemctl disable systemd-resolved - 还原
/etc/resolv.conf为静态配置(如nameserver 8.8.8.8),确保 glibc 解析器走传统路径 - 确认
/etc/nsswitch.conf中hosts行不含resolve或myhostname等resolved相关模块
混用 nscd 和 dnsmasq 同样危险:dnsmasq 作为本地 DNS 服务器,所有查询都发给它,nscd 完全无感知——这种情况下,该清的是 dnsmasq 缓存,不是 nscd。











