Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> 關於 Linux

CentOS 7/8 開放 80/443 埠口:firewalld 與 iptables 雙模式配置指南

編輯:關於 Linux

雲服務器安全組放行後,系統防火牆仍可能攔截流量。CentOS 7/8 預設使用 firewalld,兼容 iptables 命令。本文提供 firewalld 永久規則、iptables 直接操作、驗證與故障排查全流程。

防火牆架構圖

模式一:firewalld(推薦、永久生效)

1. 開放 HTTP/HTTPS 服務(按服務名)

firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
firewall-cmd --reload

2. 開放特定埠口(按埠口號)

firewall-cmd --permanent --add-port=80/tcp
firewall-cmd --permanent --add-port=443/tcp
firewall-cmd --permanent --add-port=22/tcp   # SSH 必須保留
firewall-cmd --reload

3. 富規則:限制來源 IP

# 僅允許特定 IP 訪問 80/443
firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="203.0.113.0/24" port protocol="tcp" port="80" accept'
firewall-cmd --reload

4. 區域管理(多網卡場景)

# 查看活躍區域
firewall-cmd --get-active-zones

# 指定區域開放(如 dmz 區域)
firewall-cmd --permanent --zone=dmz --add-service=http
firewall-cmd --reload

模式二:iptables 直接操作(舊習慣、即時生效但重啟失效)

# 開放 80/443/22
iptables -I INPUT -p tcp --dport 80 -j ACCEPT
iptables -I INPUT -p tcp --dport 443 -j ACCEPT
iptables -I INPUT -p tcp --dport 22 -j ACCEPT

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

# 重啟服務
systemctl restart iptables

驗證與故障排查

1. 查看當前規則

# firewalld
firewall-cmd --list-all
firewall-cmd --list-all-zones

# iptables
iptables -nL --line-numbers
iptables -nL INPUT --line-numbers

2. 測試埠口連通性

# 本機測試
curl -I https://localhost
telnet localhost 80
nc -zv localhost 80 443

# 遠端測試
nc -zv SERVER_IP 80 443
nmap -p 80,443 SERVER_IP

3. 常見問題

現象原因解決
雲控制台已放行但不通系統防火牆攔截按本文配置 firewalld/iptables
firewall-cmd 報錯 FirewallD is not running服務未啟動systemctl enable --now firewalld
iptables save 後重啟失效firewalld 覆蓋規則統一用 firewalld,或 systemctl disable firewalld
Docker 容器埠口衝突Docker 直接操作 iptables配置 Docker --iptables=false 或用 firewalld 管理

生產環境最佳實踐

  1. 統一用 firewalld,避免與 Docker、kube-proxy 衝突
  2. 按服務名開放(--add-service=http)而非埠口,語義清晰、自動適配 IPv6
  3. 最小權限原則:僅開放業務必要埠口,管理埠口 (SSH 22) 限制來源 IP
  4. 配置管理化:將規則寫入 Ansible playbook / Terraform,避免手工配置漂移
  5. 定期審計:firewall-cmd --list-all-zones 輸出存證

總結

CentOS 7/8 開放 80/443 核心是:**雲安全組 + 系統 firewalld 雙層放行**。首選 firewall-cmd --permanent --add-service=http --add-service=https,--reload 生效。拒絕直接操作 iptables 除非排查兼容性問題。將防火牆規則納入基礎設施代碼管理,實現版本控制、審計追溯、自動化部署。

Copyright © Windows教程網 All Rights Reserved