Debian 域名解析步骤
一 明确目标与环境
- 明确你的目标是把本机作为DNS 客户端使用上游 DNS,还是在本地搭建权威/缓存 DNS 服务器(如 BIND9)。
- 准备网络信息:本机 IP、上游 DNS(如 8.8.8.8/8.8.4.4)、如需自建 DNS 则准备域名与对应的记录(A、AAAA、CNAME、MX 等)。
- 规划解析顺序与安全:确认是否优先读取 /etc/hosts,以及是否限制查询来源、是否开启 DNSSEC 等。
二 作为 DNS 客户端进行解析(推荐大多数场景)
- 配置解析器
- 使用传统方式:编辑 /etc/resolv.conf,添加上游 DNS
- nameserver 8.8.8.8
- nameserver 8.8.4.4
- 使用 systemd-resolved(若系统启用):编辑 /etc/systemd/resolved.conf
- DNS=8.8.8.8 8.8.4.4
- 执行:sudo systemctl restart systemd-resolved
- 使用 resolvconf(若系统安装):确保接口配置中使用 dns-nameservers 或在 resolvconf 配置中写入 DNS。
- 配置解析顺序
- 编辑 /etc/nsswitch.conf,确保包含:hosts: files dns(先查本地 hosts,再查 DNS)。
- 验证
- dig example.com +short
- nslookup example.com
- 查看当前生效的解析器:cat /etc/resolv.conf 或 resolvectl status。
三 搭建本地 DNS 服务器 BIND9(权威或缓存转发)
- 安装软件
- sudo apt update && sudo apt install bind9 dnsutils
- 基本配置
- 编辑 /etc/bind/named.conf.options
- 设置监听:listen-on { any; }; listen-on-v6 { any; };
- 允许查询网段:allow-query { localhost; 192.168.31.0/24; };
- 转发未命中域:forwarders { 8.8.8.8; 8.8.4.4; };
- 安全与校验:dnssec-validation auto;
- 定义区域
- 编辑 /etc/bind/named.conf.local 添加正向区域
- zone “example.com” { type master; file “/etc/bind/zones/db.example.com”; };
- 可选:添加反向区域(示例网段 192.168.31.0/24)
- zone “31.168.192.in-addr.arpa” { type master; file “/etc/bind/zones/db.192.168.31”; };
- 创建区域数据文件
- sudo mkdir -p /etc/bind/zones
- 正向示例(/etc/bind/zones/db.example.com)
$TTL 604800
@ IN SOA ns1.example.com. admin.example.com. (
2025112701 ; Serial
604800 ; Refresh
86400 ; Retry
2419200 ; Expire
604800 ) ; Negative Cache TTL
@ IN NS ns1.example.com.
ns1 IN A 192.168.31.10
www IN A 192.168.31.20
- 反向示例(/etc/bind/zones/db.192.168.31)
$TTL 604800
@ IN SOA ns1.example.com. admin.example.com. (
2025112701 ; Serial
604800 ; Refresh
86400 ; Retry
2419200 ; Expire
604800 ) ; Negative Cache TTL
@ IN NS ns1.example.com.
10 IN PTR ns1.example.com.
20 IN PTR www.example.com.
- 校验与启动
- named-checkconf
- named-checkzone example.com /etc/bind/zones/db.example.com
- named-checkzone 31.168.192.in-addr.arpa /etc/bind/zones/db.192.168.31
- sudo systemctl restart bind9 && sudo systemctl enable bind9
- 防火墙
- 放行 UDP/TCP 53(DNS 查询与区域传输常用端口)。
四 在域名注册商添加 DNS 记录(对外服务)
- 购买域名并获取服务器 公网 IP。
- 在注册商管理面板添加记录(示例)
- A 记录:主机记录 www,值 203.0.113.10
- CNAME 记录:主机记录 blog,值 example.com
- 如需邮件:MX 记录指向你的邮件服务器域名
- 等待 TTL 过期后全球生效,使用 dig 或 nslookup 验证。
五 本地测试与常见问题排查
- 基本测试
- dig example.com ANY +noall +answer
- nslookup -type=MX example.com
- host www.example.com
- 解析顺序与本地覆盖
- 确认 /etc/nsswitch.conf 为 hosts: files dns
- 临时本地覆盖可编辑 /etc/hosts(如 127.0.0.1 test.example.com)
- 配置语法与服务状态
- named-checkconf /etc/bind/named.conf
- named-checkzone example.com /path/to/db.example.com
- sudo systemctl status bind9;查看日志:journalctl -u bind9 -f
- 网络连通与防火墙
- ss -lunpt | grep :53
- 确保云服务器安全组/本机防火墙放行 UDP/TCP 53。