dnsmasq是更优选择,因其支持可配置ttl缓存、按域名指定上游dns、无缝集成/etc/hosts实现内网解析,且避免与docker等服务冲突;而systemd-resolved功能受限、缓存不可调、易引发端口和配置冲突。

Linux 本地 DNS 缓存服务的核心目标是减少重复查询、降低解析延迟、减轻上游 DNS 压力。最常用且轻量可靠的方案是 dnsmasq,它不依赖复杂区域文件,适合单机或小型局域网,比 BIND9 简洁高效得多。
为什么优先选 dnsmasq 而不是 systemd-resolved?
systemd-resolved 默认监听 127.0.0.53:53,功能有限:不能自定义上游服务器顺序、缓存时间不可调、不支持 hosts 增强规则、常与 Docker 或其他 DNS 服务冲突。而 dnsmasq 提供:
- 可配置的 TTL 缓存窗口(min-cache-ttl / max-cache-ttl)
- 支持按域名指定上游 DNS(如国内域名走 114.114.114.114,国外走 8.8.8.8)
- 无缝集成 /etc/hosts,可实现内网域名本地解析
- 低内存占用(通常
安装与基础配置(Debian/Ubuntu 及 RHEL/CentOS)
先停用 systemd-resolved 避免端口冲突:
sudo systemctl disable --now systemd-resolved sudo rm -f /etc/resolv.conf echo "nameserver 127.0.0.1" | sudo tee /etc/resolv.conf sudo chattr +i /etc/resolv.conf
再安装 dnsmasq:
- Ubuntu/Debian:
sudo apt update && sudo apt install dnsmasq -y - RHEL/CentOS:
sudo yum install epel-release && sudo yum install dnsmasq -y
编辑主配置文件 /etc/dnsmasq.conf,关键项建议如下:
listen-address=127.0.0.1,192.168.1.1 # 监听本机及内网(如需局域网共享) bind-interfaces # 绑定到指定接口,更安全 cache-size=1500 # 缓存条目数,够日常使用 no-resolv # 不读取 /etc/resolv.conf server=114.114.114.114 # 国内默认上游 server=8.8.8.8 # 备用上游(可加多个) min-cache-ttl=1800 # 至少缓存30分钟(覆盖部分短TTL记录) max-cache-ttl=86400 # 最长缓存24小时
进阶实用技巧
让缓存更贴合实际需求:
-
按域名分流上游:添加
server=/cn/114.114.114.114和server=/google.com/8.8.8.8,实现智能路由 -
强制本地解析:在
/etc/hosts中添加192.168.1.100 gitlab.local,dnsmasq 默认读取并缓存(无需改配置) -
屏蔽广告域名:添加
address=/doubleclick.net/0.0.0.0,直接返回空响应 -
验证是否生效:用
dig google.com @127.0.0.1查看 SERVER 和 QUERY TIME;首次较慢,二次应明显缩短
验证与维护
启动服务并检查状态:
sudo systemctl enable --now dnsmasq sudo systemctl status dnsmasq sudo ss -tuln | grep ':53'
查看实时缓存命中情况:
- 访问
http://127.0.0.1:8080(需启用enable-tftp并配 web 界面,非默认) - 更简单方式:
sudo dnsmasq --test检查配置语法;sudo journalctl -u dnsmasq -n 20查日志 - 清空缓存:
sudo systemctl restart dnsmasq(无单独 flush 命令)











