温馨提示×

centos iptables如何与firewalld共存

小樊
45
2026-08-18 05:55:42
栏目: 智能运维

CentOS 7/8 中,iptables 与 firewalld 不能直接“共存”同时生效,因为它们的底层机制存在冲突。下面分情况说明,并给出可行方案


一、核心结论(先看这个)

firewalld 和 iptables 服务不能同时运行
iptables 命令(netfilter)与 firewalld 可以“间接共存”

原因:

  • firewalld 是一个 动态管理 netfilter 的用户态工具
  • iptables-service 是直接写 静态规则
  • 两者都会操作 同一套 netfilter 规则表
  • 同时启用会 互相覆盖规则

二、CentOS 中三种防火墙形态

方式 说明 是否推荐
firewalld CentOS 7/8 默认 ✅ 推荐
iptables-service 传统方式 ⚠️ 仅兼容
手写 iptables 命令 临时 ❌ 不建议长期

三、正确的“共存”方式(推荐)

✅ 方案一:只用 firewalld(最推荐)

systemctl status firewalld
systemctl start firewalld
systemctl enable firewalld

然后 完全不要启用 iptables 服务

systemctl disable iptables
systemctl stop iptables

✅ firewalld 本质就是 iptables/nftables 的“前端管理器”


✅ 方案二:只用 iptables(关闭 firewalld)

适合老系统或老运维习惯

systemctl stop firewalld
systemctl disable firewalld

yum install -y iptables-services
systemctl enable iptables
systemctl start iptables

规则文件:

/etc/sysconfig/iptables

四、能不能“firewalld + 手动 iptables 命令”?

⚠️ 可以,但有限制

✅ 允许的情况

  • 使用 iptables -I / -A临时调试
  • firewalld 重启后会被 清除

❌ 不允许的情况

  • 指望 iptables 规则长期生效
  • 同时运行 iptables-service

⚠️ firewalld reload 会清空你手写的 iptables 规则


五、如果你“必须”让 iptables 规则生效(正确姿势)

✅ 方法 1:通过 firewalld 的 rich rule(推荐)

firewall-cmd --add-rich-rule='
  rule family="ipv4" source address="192.168.1.100" port port="8080" protocol="tcp" accept'

✅ 方法 2:使用 firewalld 的 direct rules(接近 iptables)

firewall-cmd --direct --add-rule ipv4 filter INPUT 0 \
-p tcp --dport 3306 -j ACCEPT

查看:

firewall-cmd --direct --get-all-rules

六、CentOS 8 特别说明(重要)

CentOS 8:

  • firewalld 默认使用 nftables 后端
  • 传统 iptables 实际是 兼容层
iptables -L

本质是:

nftables → iptables compatibility

七、常见错误示例(不要这样)

❌ 同时启用:

systemctl start firewalld
systemctl start iptables

❌ 写了 iptables 规则,却重启 firewalld


八、推荐决策表

场景 建议
CentOS 7/8 新系统 ✅ firewalld
老脚本依赖 iptables ✅ 关闭 firewalld
临时测试 ⚠️ 手动 iptables
生产环境 ✅ firewalld + rich/direct rule

九、一句话总结

iptables 和 firewalld 不能“同时作为服务共存”
要么 firewalld,要么 iptables-service,二选一

如果你愿意,可以告诉我:

  • CentOS 版本
  • 是想 迁移老 iptables 规则
  • 还是 和 Docker / K8s 一起用

我可以给你一套完整迁移方案

0