Linux 系統重裝或遷移後常因 DNS 設定遺失導致域名解析失敗。本文區分臨時修改 (即時生效、重開機失效)與永久修改 (持久化、跨重開機)兩大場景,針對現代 systemd-resolved/resolvconf 框架與傳統 /etc/resolv.conf 直編模式提供標準化操作流程。
sudo vim /etc/resolv.conf
內容範例:
nameserver 8.8.8.8 # Google 主 DNS
nameserver 8.8.4.4 # Google 備用 DNS
# nameserver 1.1.1.1 # Cloudflare 可作第三選項
search example.com # 搜尋域名後綴 (可選)
:wq 儲存即時生效。**警告**:檔案開頭通常標註 # Generated by NetworkManager 或 # DO NOT EDIT MANUALLY,重開機或網路服務重啟會被覆蓋。

/etc/systemd/resolved.conf:[Resolve]
DNS=8.8.8.8 8.8.4.4 1.1.1.1
FallbackDNS=1.0.0.1 9.9.9.9
# Domains=~example.com # 分割 DNS (可選)
DNSSEC=yes
DNSOverTLS=opportunistic
sudo systemctl restart systemd-resolved
/etc/resolv.conf 為 systemd-resolved 管理的符號連結:ls -l /etc/resolv.conf
# 應指向 ../run/systemd/resolve/stub-resolv.conf
# 若非連結:sudo ln -sf /run/systemd/resolve/stub-resolv.conf /etc/resolv.conf
resolvectl status
dig example.com
sudo vim /etc/resolvconf/resolv.conf.d/base
加入:
nameserver 8.8.8.8
nameserver 8.8.4.4
sudo resolvconf -u
此法透過 resolvconf 守護進程自動彙整 /etc/resolvconf/resolv.conf.d/* 產生 /etc/resolv.conf,重開機持久生效。
# 列出連線
nmcli connection show
# 修改特定連線 DNS (如 "Wired connection 1")
nmcli connection modify "Wired connection 1" ipv4.dns "8.8.8.8 8.8.4.4"
nmcli connection modify "Wired connection 1" ipv4.ignore-auto-dns yes
# 重啟連線
nmcli connection up "Wired connection 1"
# /etc/netplan/01-netcfg.yaml
network:
version: 2
renderer: networkd
ethernets:
eth0:
dhcp4: true
nameservers:
addresses: [8.8.8.8, 8.8.4.4, 1.1.1.1]
search: [example.com]
# 套用
sudo netplan apply
# 查看當前生效 DNS
cat /etc/resolv.conf
resolvectl status # systemd-resolved
nmcli dev show | grep DNS # NetworkManager
# 測試解析
dig +short example.com
nslookup example.com
host example.com
# 追蹤解析路徑
dig +trace example.com
| 提供商 | 主 DNS | 備 DNS | 特色 |
|---|---|---|---|
| 8.8.8.8 | 8.8.4.4 | 全球任何、支援 DoH/DoT | |
| Cloudflare | 1.1.1.1 | 1.0.0.1 | 隱私優先、無日誌、最快 |
| Quad9 | 9.9.9.9 | 149.112.112.112 | 安全過濾、阻擋惡意域名 |
| OpenDNS | 208.67.222.222 | 208.67.220.220 | 家長控制、防釣魚 |
| 阿里云 | 223.5.5.5 | 223.6.6.6 | 國內極速、適合中國大陸 |
| 騰訊 | 119.29.29.29 | 119.28.28.28 | 國內極速、支援 DoH |