温馨提示×

centos iptables怎样兼容firewalld

小樊
47
2026-10-02 18:08:04
栏目: 智能运维

在 CentOS 7 / 8 中,firewalld 是默认防火墙管理工具,而 iptables 仍然存在,但 firewalld 本质上也是通过 iptables(或 nftables)实现的。
要让 iptables 和 firewalld 兼容/共存,核心原则是:不要让两者同时“抢着管理”同一套规则。

下面分几种常见场景说明。


一、推荐做法(官方方式):用 firewalld 管理,iptables 只查看

1. 查看 firewalld 生成的 iptables 规则

iptables -L -n -v

你会看到 firewalld 自动生成的链(如 INPUT_ZONES、FWDI_* 等)。

✅ 这是“兼容”的最安全方式
iptables 只是“看”,不直接写规则。


二、在 firewalld 中“嵌入”iptables 规则(推荐进阶)

如果你必须用 iptables 语法,可以通过 direct rules(直连规则)。

示例:允许 8080 端口

firewall-cmd --direct --add-rule ipv4 filter INPUT 0 -p tcp --dport 8080 -j ACCEPT
firewall-cmd --runtime-to-permanent

查看:

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

✅ 优点

  • 仍由 firewalld 管理生命周期
  • 重启不会冲突

三、完全使用 iptables(关闭 firewalld)

⚠️ 不推荐服务器生产环境,但开发/测试常用

CentOS 7

systemctl stop firewalld
systemctl disable firewalld

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

写规则:

vi /etc/sysconfig/iptables
systemctl restart iptables

四、CentOS 8 特别注意(nftables)

CentOS 8:

  • firewalld 默认用 nftables
  • 老 iptables 命令是兼容层

查看真实规则:

nft list ruleset

如果你坚持用 iptables:

update-alternatives --set iptables /usr/sbin/iptables-legacy

五、常见坑总结

❌ 同时:

  • systemctl start firewalld
  • systemctl start iptables

→ 规则互相覆盖,网络异常

✅ 正确姿势:

  • firewalld 管总
  • iptables 只查或走 direct

六、结论(一句话)

CentOS 中 iptables 与 firewalld 兼容的关键是:firewalld 负责“管理”,iptables 负责“查看或直连规则”,不要两者同时写规则。

如果你能说下你是 CentOS 几 / 想做什么(端口、NAT、Docker?),我可以给你更精确的配置示例。

0 踩