需启用并配置 systemd-resolved 实现 dns 本地缓存:一、启用服务;二、链接 /etc/resolv.conf 至 stub-resolv.conf;三、编辑 resolved.conf 设置 dns 和 cache=yes;四、验证缓存命中率与响应时间;五、适配 networkmanager 避免配置冲突。

如果您希望提升 Linux 系统的 DNS 解析速度并启用本地缓存功能,则需正确配置 systemd-resolved 服务。以下是实现该目标的具体操作步骤:
一、确认 systemd-resolved 服务状态并启用
systemd-resolved 是 systemd 提供的本地 DNS 解析与缓存服务,启用后可自动缓存解析结果、减少重复查询延迟。需确保其已安装、启用并正在运行。
1、检查服务是否已安装并处于活动状态:systemctl is-active systemd-resolved
2、若返回 inactive 或未安装,执行安装命令(Ubuntu/Debian):sudo apt install systemd-resolved
3、启用并立即启动服务:sudo systemctl enable --now systemd-resolved
4、验证服务运行状态:sudo systemctl status systemd-resolved
二、配置 /etc/resolv.conf 指向 stub 解析器
为使系统所有应用通过 systemd-resolved 进行解析,必须将 /etc/resolv.conf 正确链接至其 stub-resolv.conf 文件,否则 DNS 请求将绕过缓存直接发往上游服务器。
1、删除当前 /etc/resolv.conf(若为软链接):sudo unlink /etc/resolv.conf
2、创建指向 stub 解析器的新链接:sudo ln -sf /run/systemd/resolve/stub-resolv.conf /etc/resolv.conf
3、验证链接有效性:ls -l /etc/resolv.conf,输出应显示指向 /run/systemd/resolve/stub-resolv.conf
4、确认 stub 解析器内容包含 nameserver 127.0.0.53:cat /etc/resolv.conf
三、编辑 /etc/systemd/resolved.conf 启用并优化缓存
该主配置文件控制缓存行为、DNS 服务器列表、DNSSEC 验证等关键参数。默认 Cache=yes 已开启缓存,但需显式配置上游 DNS 并确保无冲突设置。
1、使用编辑器打开配置文件:sudo nano /etc/systemd/resolved.conf
2、取消注释并修改 [Resolve] 段落,确保包含以下内容:
DNS=114.114.114.114 8.8.8.8
FallbackDNS=1.1.1.1 208.67.222.222
Cache=yes
DNSSEC=allow-downgrade
DNSOverTLS=no
3、保存退出后重启服务以加载新配置:sudo systemctl restart systemd-resolved
四、验证缓存功能是否生效
通过统计信息与实际解析测试,确认缓存机制已正常工作,包括命中率、缓存条目数及响应时间改善。
1、查看当前缓存统计:systemd-resolve --statistics
2、重点关注输出中的 Cache current entries 和 Cache hit rate percent 字段
3、执行两次相同域名解析:systemd-resolve example.com
4、对比第二次解析的 "Query time:" 值,应明显低于首次(通常 ≤ 1ms)
5、手动刷新缓存以确认控制能力:sudo systemd-resolve --flush-caches
五、适配 NetworkManager(如使用图形桌面或 DHCP 网络)
当系统使用 NetworkManager 管理网络时,其可能覆盖 systemd-resolved 的 DNS 设置。需强制 NetworkManager 将 DNS 配置推送至 resolved,避免解析路径分裂。
1、在 /etc/NetworkManager/conf.d/ 下创建配置文件:sudo nano /etc/NetworkManager/conf.d/10-dns-systemd-resolved.conf
2、写入以下内容:
[main]
dns=systemd-resolved
3、保存后重启 NetworkManager:sudo systemctl restart NetworkManager
4、验证 DNS 来源:resolvectl status,Global DNS 行应显示已配置的 DNS 地址










