安装 dnsmasq
在不同的操作系统中安装 dnsmasq 的方法如下:
在 Ubuntu 或 Debian 系统中:
sudo apt-get update sudo apt-get install dnsmasq
在 CentOS 或 Fedora 系统中:
sudo dnf install dnsmasq
在 macOS 中:
可以通过 Homebrew 安装:
brew install dnsmasq
配置基本设置
dnsmasq 的默认配置文件位于 /etc/dnsmasq.conf,如果没有自定义配置文件,可以直接修改默认文件或创建一个新的配置文件。
创建或修改配置文件:
sudo nano /etc/dnsmasq.conf
配置基本设置:
interface=eth # 仅在 eth 接口上工作 server=192.168.1.1 # DNS 服务器地址 domain=example.com # 默认域名
设置 DNS 记录
在 dnsmasq 配置文件中,添加 DNS 记录:
添加 A 记录:
host=192.168.1.100,example.com
这会将 example.com 映射到 168.1.100。
添加 CNAME 记录:
cname=www.example.com,example.com
这会将 www.example.com 映射到 example.com。
添加 MX 记录:
mx=mail.example.com,example.com
这会将邮件域 example.com 车向 mail.example.com。
配置 NAT
dnsmasq 也可以作为 NAT 服务器,用于内部设备访问外部网络。
添加端口转换:
--option-file=/etc/dnsmasq-nat.conf
在 /etc/dnsmasq-nat.conf 文件中添加 NAT 规则:
port-forward=808:80,192.168.1.100:80
这会将外部连接的 HTTP 请求(目标端口 80)转换到内部设备 168.1.100 的 HTTP 请求。
启动 dnsmasq 服务器:
sudo dnsmasq --conf-file=/etc/dnsmasq.conf --option-file=/etc/dnsmasq-nat.conf
高级配置
以下是一些高级配置选项:
启用 DNS 过滤:
filter=
可以根据需求添加过滤规则,例如阻止访问某些网站。
设置 DNS 缓存:
cache-size=100
设置缓存大小,缓存 DNS 查询结果。
配置 TTL(Time to Live):
ttl=60
设置 DNS 记录的 TTL(分钟)。
优化和故障排除
调整 dnsmasq 的线程数:
sudo dnsmasq --num-threads=4
默认是单线程,可以根据负载调整线程数。
故障排除:
- dnsmasq 服务无法启动,检查配置文件中的错误。
- DNS 查询速度慢,可能需要增加缓存大小或优化服务器性能。
启动和停止 dnsmasq
启动 dnsmasq:
sudo dnsmasq --conf-file=/etc/dnsmasq.conf
停止 dnsmasq:
sudo dnsmasq --no-daemon
通过以上配置,dnsmasq 可以作为一个功能强大的 DNS 和 DHCP 服务器,同时支持 NAT 转换,根据实际需求,可以进一步调整配置参数。




