CentOS 中 iptables 规则不生效 是一个非常常见的问题,通常不是因为 iptables 本身坏了,而是被其他机制覆盖或干扰。下面按 最常见原因 → 排查方法 → 解决方案 系统说明。
CentOS 7/8 默认使用 firewalld,它会接管 netfilter,导致你手动写的 iptables 规则:
systemctl status firewalld
✅ 方案 A:停用 firewalld,使用 iptables(传统方式)
systemctl stop firewalld
systemctl disable firewalld
然后启用 iptables 服务(CentOS 7):
yum install -y iptables-services
systemctl enable iptables
systemctl start iptables
✅ 方案 B:继续使用 firewalld(推荐) 不要再直接写 iptables,而是用:
firewall-cmd --add-port=80/tcp --permanent
firewall-cmd --reload
iptables 顺序非常重要
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
iptables -A INPUT -j DROP
✅ 正确顺序:
❌ 错误顺序:
iptables -nvL INPUT --line-number
iptables 规则 默认在内存中,重启即失效。
service iptables save
# 或
iptables-save > /etc/sysconfig/iptables
systemctl enable iptables
iptables 默认是 filter 表,但你可能想做的是 NAT。
| 需求 | 表 |
|---|---|
| 防火墙 | filter |
| 端口转发 | nat |
| 流量修改 | mangle |
iptables -t nat -A PREROUTING -p tcp --dport 8080 -j REDIRECT --to-port 80
Docker 会自动修改 iptables
iptables -nvL
--iptables=false(不推荐)确认不是以下问题:
ip addr
ip route
ss -lntp
例如:
# 1. 是否启用 firewalld
systemctl status firewalld
# 2. iptables 是否运行
systemctl status iptables
# 3. 查看规则
iptables -nvL
# 4. 查看 nat 表
iptables -t nat -nvL
# 5. 是否保存
cat /etc/sysconfig/iptables
| CentOS 版本 | 默认防火墙 |
|---|---|
| CentOS 6 | iptables |
| CentOS 7 | firewalld |
| CentOS 8 | firewalld |
| CentOS Stream | firewalld |
✅ 新系统:用 firewalld
✅ 老系统 / 脚本兼容:用 iptables-services
❌ 不要 firewalld 和 iptables 混用
你可以直接贴出:
iptables -nvL 输出我可以 直接帮你把规则写对 ✅