插件窝 干货文章 Linux下如何用dnsmasq做dns cache server配置

Linux下如何用dnsmasq做dns cache server配置

dnsmasq 服务器 sudo 缓存 210    来源:    2025-04-25

在Linux下使用dnsmasq配置DNS缓存服务器

dnsmasq是一个轻量级的DNS转发器和DHCP服务器,非常适合用作本地DNS缓存服务器。以下是配置步骤:

1. 安装dnsmasq

在大多数Linux发行版上,可以使用包管理器安装:

# Debian/Ubuntu
sudo apt-get install dnsmasq

# CentOS/RHEL
sudo yum install dnsmasq

# Fedora
sudo dnf install dnsmasq

# Arch Linux
sudo pacman -S dnsmasq

2. 基本配置

编辑dnsmasq的主配置文件(通常位于/etc/dnsmasq.conf):

sudo nano /etc/dnsmasq.conf

进行以下基本配置:

# 监听地址(设置为0.0.0.0监听所有接口,或指定IP)
listen-address=127.0.0.1,192.168.1.100

# 不读取/etc/hosts文件(纯DNS缓存模式)
no-hosts

# 不读取/etc/resolv.conf中的上游DNS服务器
no-resolv

# 指定上游DNS服务器(例如Google DNS)
server=8.8.8.8
server=8.8.4.4

# 缓存大小(默认150,可根据需要调整)
cache-size=1000

# 启用日志
log-queries
log-facility=/var/log/dnsmasq.log

3. 高级配置选项(可选)

# 最小TTL值(秒)
min-cache-ttl=300

# 最大TTL值(秒)
max-cache-ttl=3600

# 本地域名解析(如果有本地网络需要解析)
local=/example.local/

# 禁止解析某些域名
address=/doubleclick.net/127.0.0.1

# 启用DNS查询转发
domain-needed
bogus-priv

4. 启动和启用dnsmasq服务

# 启动服务
sudo systemctl start dnsmasq

# 设置开机启动
sudo systemctl enable dnsmasq

# 检查状态
sudo systemctl status dnsmasq

5. 配置客户端使用DNS缓存服务器

修改客户端设备的网络设置,将DNS服务器指向运行dnsmasq的服务器IP地址。

6. 验证配置

# 检查dnsmasq是否正常运行
sudo netstat -tulnp | grep dnsmasq

# 测试DNS查询
dig example.com @127.0.0.1

# 查看缓存统计
sudo killall -SIGUSR1 dnsmasq
sudo tail -f /var/log/dnsmasq.log

7. 防火墙配置(如果需要)

如果dnsmasq服务器需要为其他客户端提供服务,确保防火墙允许UDP 53端口:

# 使用iptables
sudo iptables -A INPUT -p udp --dport 53 -j ACCEPT

# 使用firewalld
sudo firewall-cmd --add-service=dns --permanent
sudo firewall-cmd --reload

# 使用ufw
sudo ufw allow 53/udp

8. 性能调优

对于高负载环境,可以调整以下参数:

# 增加缓存大小
cache-size=5000

# 增加同时处理的查询数量
dns-forward-max=500

# 禁用IPv6(如果不需要)
no-ipv6

通过以上配置,你就可以拥有一个功能完善的本地DNS缓存服务器,可以显著提高DNS查询速度并减少对外部DNS服务器的依赖。