Linux系统默认无全局DNS缓存,需启用systemd-resolved或dnsmasq等服务实现本地缓存;先通过ls -l /etc/resolv.conf、resolvectl status和systemctl is-active确认解析器,再针对性启用并配置,最后用resolvectl statistics或dig验证缓存效果。

Linux系统默认不自带全局DNS缓存,但可通过启用systemd-resolved、dnsmasq等服务实现本地缓存,从而显著减少重复域名查询延迟,提升网页打开、软件更新、容器拉取等网络操作响应速度。
确认当前DNS解析机制
先判断系统实际用的是哪个解析器,避免盲目操作导致DNS失效。
执行ls -l /etc/resolv.conf:若指向/run/systemd/resolve/stub-resolv.conf,说明systemd-resolved已接管;若指向/run/NetworkManager/resolv.conf,则NetworkManager在控制;若直接是普通文件且含nameserver行,则可能被手动配置或由其他服务覆盖。
运行resolvectl status:观察输出中“DNS Servers”和“Cache”字段。若显示“Cache: yes”且“Cache hits”有计数,说明systemd-resolved缓存已生效。
执行systemctl is-active systemd-resolved:返回active表示服务正在运行;若为inactive,后续启用步骤必须执行。
【关键前提】若resolvectl status报错“Failed to get global data: Unit systemd-resolved.service not found”,说明该服务未安装,需先运行sudo apt install systemd-resolved(Debian/Ubuntu)或sudo yum install systemd(RHEL/CentOS)。
启用并配置systemd-resolved缓存
这是现代主流发行版(Ubuntu 20.04+、Fedora 33+、CentOS 8+)的推荐方案,无需额外安装,集成度高,配置简洁。
第一步:启用服务并启动
运行sudo systemctl enable --now systemd-resolved。这一步会自动创建服务单元、生成运行时目录,并立即启动守护进程。
Linux AI 服务器 — 将 Linux 服务器转换为本地 AI 推理集群。使用 systemd、NVIDIA CUDA 实现无头 Linux AI,零 GUI 开销。
第二步:修复/etc/resolv.conf链接
执行sudo ln -sf /run/systemd/resolve/stub-resolv.conf /etc/resolv.conf。这确保所有应用(curl、apt、浏览器)都通过127.0.0.53这个stub解析器发请求,否则缓存形同虚设。
第三步:配置上游DNS与缓存策略
用sudo nano /etc/systemd/resolved.conf打开配置文件,在[Resolve]段落下添加或取消注释以下三行:DNS=114.114.114.114 8.8.8.8FallbackDNS=1.1.1.1Cache=yes
保存后执行sudo systemctl restart systemd-resolved使配置生效。
验证是否成功:运行resolvectl statistics,查看“Cache hits”是否随后续域名查询(如ping baidu.com)而增长;再执行dig @127.0.0.53 google.com +short,若返回IP且无报错,说明stub解析器工作正常。
部署dnsmasq作为替代缓存方案
当你需要更精细控制(如自定义hosts、TTL强制、内网域名重写、DHCP集成),或systemd-resolved与NetworkManager冲突严重时,dnsmasq是更灵活的选择。
方法一:基础安装与启用
执行sudo apt install dnsmasq(Debian/Ubuntu)或sudo yum install dnsmasq(RHEL/CentOS)。安装完成后,默认已禁用,需手动启用:sudo systemctl enable --now dnsmasq。
方法二:最小化缓存配置
编辑/etc/dnsmasq.conf,确保包含以下四行(其余可注释):cache-size=1000no-resolvserver=8.8.8.8listen-address=127.0.0.1
其中no-resolv防止dnsmasq读取/etc/resolv.conf造成循环;listen-address限定只响应本地请求,更安全。
方法三:切换系统DNS指向dnsmasq
执行echo "nameserver 127.0.0.1" | sudo tee /etc/resolv.conf。这一步会覆盖原有配置,【不可逆操作】请提前备份原文件:sudo cp /etc/resolv.conf /etc/resolv.conf.bak。
测试缓存效果:运行dig @127.0.0.1 github.com | grep "Query time"两次,第二次“Query time”应明显低于第一次(如从28ms降至1ms),即表示缓存命中。

















