DNS(Domain Name System)是互聯網的「電話簿」,將人類易記的域名(如 www.example.com)解析為機器可路由的 IP 地址(如 93.184.216.34)。Linux 系統通過 /etc/resolv.conf 指定使用的 DNS 服務器。
# 域名搜尋後綴(可選)
search example.com corp.example.com
# 主域名後綴(可選)
domain example.com
# DNS 服務器地址(按優先序)
nameserver 192.168.1.1
nameserver 8.8.8.8
nameserver 1.1.1.1
# 選項(可選)
options timeout:2 attempts:3 rotate single-request-reopen
| 指令 | 作用 | 範例 |
|---|---|---|
| nameserver | 指定 DNS 服務器 IP | nameserver 8.8.8.8 |
| search | 主機名補全搜尋列表 | search corp.local → 輸入 "server" 實際查 "server.corp.local" |
| domain | 本機所屬域名 | domain example.com |
| options | 調整解析行為 | options timeout:1 attempts:2 |
傳統靜態編輯 /etc/resolv.conf 在現代發行版(systemd-resolved、NetworkManager、Netplan)中已被取代:
# 查看當前 DNS 狀態
resolvectl status
# 臨時設置 DNS(重啟失效)
resolvectl dns eth0 8.8.8.8 1.1.1.1
# 永久配置:編輯 /etc/systemd/resolved.conf
[Resolve]
DNS=8.8.8.8 1.1.1.1
FallbackDNS=9.9.9.9
Domains=~.
DNSSEC=yes
DNSOverTLS=opportunistic
# 重啟生效
systemctl restart systemd-resolved
# 圖形界面:nm-connection-editor
# 命令行:
nmcli con mod "Wired connection 1" ipv4.dns "8.8.8.8,1.1.1.1"
nmcli con mod "Wired connection 1" ipv4.ignore-auto-dns yes
nmcli con up "Wired connection 1"
# /etc/netplan/01-netcfg.yaml
network:
version: 2
renderer: networkd
ethernets:
eth0:
dhcp4: true
nameservers:
addresses: [8.8.8.8, 1.1.1.1]
search: [corp.local]
# 生效
netplan apply
# 基本查詢
dig example.com
# 指定 DNS 服務器
dig @8.8.8.8 example.com
# 查詢特定記錄類型
dig example.com MX
dig example.com TXT
dig example.com AAAA
# 追蹤完整解析鏈路
dig +trace example.com
# 簡潔輸出(腳本友好)
dig +short example.com
nslookup example.com
nslookup -type=MX example.com
nslookup example.com 8.8.8.8
host example.com
host -t MX example.com
host -v example.com
resolvectl query example.com
resolvectl statistics
# 檢查宿主機 DNS
cat /etc/resolv.conf
# 啟動容器時指定 DNS
docker run --dns=8.8.8.8 --dns=1.1.1.1 ...
# 或配置 daemon.json
{ "dns": ["8.8.8.8", "1.1.1.1"] }
# 方案:配置分流解析
# systemd-resolved 支援按域名路由
# /etc/systemd/resolved.conf
[Resolve]
Domains=~corp.internal
DNS=10.0.0.1
# 對比多個 DNS 服務器結果
for dns in 8.8.8.8 1.1.1.1 9.9.9.9 114.114.114.114; do
echo "=== $dns ==="
dig @$dns example.com +short
done
/etc/resolv.conf 實際生效內容(resolvectl status 或 cat /run/systemd/resolve/resolv.conf)