温馨提示×

为何CentOS iptables不生效

小樊
43
2026-08-03 00:34:24
栏目: 智能运维

CentOS 中 iptables 规则不生效 是一个非常常见的问题,通常不是因为 iptables 本身坏了,而是被其他机制覆盖或干扰。下面按 最常见原因 → 排查方法 → 解决方案 系统说明。


一、最常见原因(按出现概率排序)

1️⃣ firewalld 正在运行(最常见)

CentOS 7/8 默认使用 firewalld,它会接管 netfilter,导致你手动写的 iptables 规则:

  • 不生效
  • 重启后被清空
  • 或被 firewalld 覆盖

检查

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

2️⃣ 规则写错链 / 顺序错误

iptables 顺序非常重要

常见错误

iptables -A INPUT -p tcp --dport 22 -j ACCEPT
iptables -A INPUT -j DROP

✅ 正确顺序:

  • 先允许
  • 再拒绝

❌ 错误顺序:

  • 先 DROP
  • 再 ACCEPT(永远不会命中)

查看当前规则顺序

iptables -nvL INPUT --line-number

3️⃣ 规则未保存,重启后丢失

iptables 规则 默认在内存中,重启即失效。

保存规则

service iptables save
# 或
iptables-save > /etc/sysconfig/iptables

确认开机加载

systemctl enable iptables

4️⃣ 规则写在了错误的表

iptables 默认是 filter 表,但你可能想做的是 NAT。

需求
防火墙 filter
端口转发 nat
流量修改 mangle

示例(端口转发)

iptables -t nat -A PREROUTING -p tcp --dport 8080 -j REDIRECT --to-port 80

5️⃣ 被 Docker / Kubernetes 覆盖

Docker 会自动修改 iptables

表现

  • 手动规则被清空
  • 端口仍然能访问
  • DOCKER 链存在

检查

iptables -nvL

解决

  • 不要和 Docker 抢 filter 表
  • 使用 --iptables=false(不推荐)
  • 或在 DOCKER-USER 链加规则

6️⃣ 网络不通不是 iptables 的问题

确认不是以下问题:

ip addr
ip route
ss -lntp

例如:

  • 服务没监听
  • 监听在 127.0.0.1
  • 云服务器安全组没放行

二、快速排查清单(一步一步来)

# 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 版本 默认防火墙
CentOS 6 iptables
CentOS 7 firewalld
CentOS 8 firewalld
CentOS Stream firewalld

四、推荐做法(重要)

新系统:用 firewalld
老系统 / 脚本兼容:用 iptables-services
不要 firewalld 和 iptables 混用


五、如果你愿意,我可以进一步帮你

你可以直接贴出:

  1. CentOS 版本
  2. iptables -nvL 输出
  3. 你想实现什么(放行端口 / 转发 / 限速 / 防攻击)

我可以 直接帮你把规则写对

0