搭建 DNS 服务器(常见于内网解析、缓存加速或本地开发测试)并不复杂,根据你的需求和使用环境,主流方案有几种,下面以最常见的Linux (Ubuntu/Debian) 环境为例,介绍两种主流搭建方式。
1. 快速搭建:使用dnsmasq (推荐内网/开发环境)
dnsmasq 配置简单、资源占用低,适合局域网 DNS 缓存或本地主机名解析。
安装
sudo apt update
sudo apt install dnsmasq -y基本配置(编辑/etc/dnsmasq.conf)
开启本地监听(取消注释或添加)
listen-address=127.0.0.1
# 如果需要局域网其他机器使用,添加本机IP,192.168.1.100
listen-address=192.168.1.100添加本地域名解析(直接将自定义域名指向内网IP)
在文件末尾添加:
address=/myserver.local/192.168.1.100
address=/test.dev/127.0.0.1 这样访问myserver.local 就会解析到192.168.1.100。
指定上游 DNS(默认可不配,自动读/etc/resolv.conf,你也可手动指定)
server=8.8.8.8
server=114.114.114.114启用缓存(默认已开启,可自行调整大小)
cache-size=1000启动与测试
sudo systemctl restart dnsmasq
# 测试本机解析
nslookup myserver.local 127.0.0.1
dig @127.0.0.1 test.dev2. 功能完整:使用BIND 9 (生产环境/权威DNS)
BIND 是互联网上最流行的 DNS 服务器软件,功能强大但配置稍复杂,适合需要管理正式域名记录 (A, CNAME, MX等) 的场景。
安装
sudo apt update
sudo apt install bind9 bind9utils bind9-doc -y核心配置文件/etc/bind/named.conf(通常引用以下三个文件,建议使用本地配置/etc/bind/named.conf.local)
配置一个正向区域 (解析example.com)
1.编辑named.conf.local:
zone "example.com" {
type master;
file "/etc/bind/db.example.com";
}; 2.创建区域数据库文件/etc/bind/db.example.com:
$TTL 604800
@ IN SOA ns1.example.com. admin.example.com. (
2 ; Serial
604800 ; Refresh
86400 ; Retry
2419200 ; Expire
604800 ) ; Negative Cache TTL
;
@ IN NS ns1.example.com.
@ IN A 192.168.1.10 ; 主域名
ns1 IN A 192.168.1.10 ; 域名服务器
www IN A 192.168.1.20 ; www
mail IN A 192.168.1.30 ; 邮件服务器配置一个反向区域 (解析IP到域名)
1.在named.conf.local 中添加(假设网段是192.168.1):
zone "1.168.192.in-addr.arpa" {
type master;
file "/etc/bind/db.192.168.1";
}; 2.创建文件/etc/bind/db.192.168.1:
$TTL 604800
@ IN SOA ns1.example.com. admin.example.com. (
1 ; Serial
604800 ; Refresh
86400 ; Retry
2419200 ; Expire
604800 ) ; Negative Cache TTL
;
@ IN NS ns1.example.com.
10 IN PTR ns1.example.com. ; .10 -> ns1
20 IN PTR www.example.com. ; .20 -> www启动与测试
sudo systemctl restart bind9
sudo systemctl enable bind9
# 测试正向解析
dig @127.0.0.1 www.example.com
# 测试反向解析
dig @127.0.0.1 -x 192.168.1.20如果你使用的是 Windows Server,可通过服务器管理器 -> 添加角色和功能 -> DNS 服务器 来安装,安装后通过dnsmgmt.msc 管理控制台添加“正向查找区域”和“反向查找区域”,操作界面化,相对直观。
1、防火墙放行:
# Ubuntu 防火墙
sudo ufw allow 53/tcp
sudo ufw allow 53/udp
# 如果需要在局域网使用,还需允许对应网段2、防止被利用为开放DNS反射攻击源(重要!):
对于BIND,在/etc/bind/named.conf.options 中添加
options {
// 只允许局域网或特定IP段查询
allow-query { 127.0.0.1; 192.168.1.0/24; };
// 只允许本机或可信DNS服务器发起递归查询
recursion yes;
allow-recursion { 127.0.0.1; 192.168.1.0/24; };
};对于dnsmasq,在配置文件中添加
# 只允许本机和局域网
bind-interfaces
except-interface=lo
# 或者使用 listen-address 限制3、日志与排错:
BIND 日志sudo tail -f /var/log/syslog | grep named
dnsmasq 日志默认不开启,可在配置中加log-queries 和log-facility=/var/log/dnsmasq.log
| 场景 | 推荐方案 | 理由 |
| 临时测试、本地开发、简单内网解析 | dnsmasq | 配置只需2-3行,秒搭 |
| 生产环境、需要管理正式域名 | BIND 9 | 功能完整、久经考验 |
| Windows Server 环境 | Windows DNS 角色 | 图形化,与AD域集成好 |
| Linux 下的轻量级权威DNS | Knot DNS /PowerDNS | 性能更高,但学习曲线稍陡 |
操作建议:初学者可以从dnsmasq 开始尝试,了解基本概念后,再根据自己的网络需求决定是否升级到 BIND 或 Windows DNS,务必记得配置访问控制(allow-query) 以防止被恶意利用。
文章摘自:https://idc.huochengrm.cn/dns/25515.html
评论