Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學

Linux 能 Ping 通 IP 卻 Ping 不通域名:防火牆攔截 DNS 53 端口排查實錄

編輯:Linux 系統常見問題解答

經典網絡故障:ping 8.8.8.8 通,ping www.baidu.com 不通。直覺以為是 DNS 服務器配置錯誤,實際卻是防火牆攔截了 DNS 回應包(UDP 53 端口)。本文記錄完整排查鏈路與 iptables 修復規則。

故障現場

# 域名解析配置看起來正常
cat /etc/resolv.conf
nameserver 202.96.209.133
nameserver 10.202.72.118
nameserver 114.114.114.114
nameserver 8.8.8.8

# 路由表正常,默認網關可達
netstat -rn
# 或 route -n
default 115.28.83.247 0.0.0.0 UG 0 0 0 eth1

# nsswitch.conf 解析順序正常
grep hosts /etc/nsswitch.conf
hosts: dns files

排查過程

  1. 確認 DNS 服務器可達:ping 114.114.114.114 通,telnet 114.114.114.114 53 通(或 nc -vzu 114.114.114.114 53)。
  2. 抓包分析:tcpdump -i eth1 -nn port 53 發現:客戶端發出 DNS 查詢(UDP 53),但**無任何回應包返回**。
  3. 檢查防火牆:iptables -L -n -v 發現 INPUT 鏈默認策略 DROP,且無允許 UDP 53 入站規則。
  4. 驗證假設:臨時關閉防火牆 service iptables stop,ping www.baidu.com 即通。確認為防火牆攔截 DNS 回應。

根因分析

DNS 查詢使用 UDP 協議,客戶端發送請求到服務器 53 端口(目標端口 53,源端口隨機高位端口),服務器回應時**源端口 53,目標端口為客戶端的隨機高位端口**。若防火牆只允許「目標端口 53」入站,會攔截「源端口 53」的回應包。需同時放行:

  • 出站:目標端口 53(查詢請求)
  • 入站:源端口 53(查詢回應)

修復規則(iptables)

# 允許 DNS 查詢請求出站(目標端口 53)
iptables -A OUTPUT -p udp --dport 53 -j ACCEPT

# 允許 DNS 查詢回應入站(源端口 53)
iptables -A INPUT -p udp --sport 53 -j ACCEPT

# 若服務器本身也運行 DNS 服務(如 bind、dnsmasq),還需允許入站目標端口 53、出站源端口 53
iptables -A INPUT -p udp --dport 53 -j ACCEPT
iptables -A OUTPUT -p udp --sport 53 -j ACCEPT

# 同理處理 TCP 53(區域傳輸、大回應回退 TCP)
iptables -A OUTPUT -p tcp --dport 53 -j ACCEPT
iptables -A INPUT -p tcp --sport 53 -j ACCEPT
iptables -A INPUT -p tcp --dport 53 -j ACCEPT
iptables -A OUTPUT -p tcp --sport 53 -j ACCEPT

# 保存規則(CentOS/RHEL)
service iptables save
# 或 iptables-save > /etc/sysconfig/iptables

# Ubuntu/Debian (iptables-persistent)
netfilter-persistent save

firewalld / ufw 現代工具寫法

# firewalld (CentOS 7+, RHEL 7+, Fedora)
firewall-cmd --permanent --add-service=dns
firewall-cmd --reload

# ufw (Ubuntu/Debian)
ufw allow 53/udp
ufw allow 53/tcp
ufw reload

驗證修復

# 域名解析測試
dig www.baidu.com
# 或
nslookup www.baidu.com
# 或
ping -c 3 www.baidu.com

# 確認防火牆規則生效
iptables -L -n -v | grep 53

經驗總結

  1. Ping 通 IP 不通域名 = 90% 是 DNS 故障,但 DNS 故障不一定是 /etc/resolv.conf 錯,可能是防火牆、SELinux、網絡設備 ACL、DNS 服務器故障、域名劫持等。
  2. UDP 狀態檢測:防火牆需識別「回應包」屬於已建立會話。iptables 可用 -m state --state ESTABLISHED,RELATED 一條規則放行所有回應,比逐端口精確。
  3. 狀態防火牆最佳實踐:
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A OUTPUT -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT
# 僅需顯式放行「主動發起的入站服務端口」(如 80, 443, 22, 53)
iptables -A INPUT -p tcp --dport 53 -j ACCEPT
iptables -A INPUT -p udp --dport 53 -j ACCEPT

此法下 DNS 回應自動匹配 ESTABLISHED 放行,無需單獨寫 --sport 53。


延伸: 若使用 systemd-resolved、dnsmasq、nscd 等本地緩存服務,確保其服務狀態正常(systemctl status systemd-resolved),並允許本地回環 53 端口通信。

Copyright © Windows教程網 All Rights Reserved