在 CentOS 中 iptables 规则重启后失效,这是一个非常常见的问题,原因主要有以下几种,取决于你使用的 CentOS 版本和网络管理方式。
iptables 规则默认是保存在内存中的,不会自动持久化。
系统重启后,iptables 会重新加载默认规则(通常是空的),所以你之前配置的规则就“消失”了。
你只是执行了类似:
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
但 没有保存。
✅ 解决方法:
service iptables save
或:
iptables-save > /etc/sysconfig/iptables
然后确认开机启动:
chkconfig iptables on
CentOS 7+ 默认使用 firewalld,即使你手动用 iptables 添加规则,重启后也会被 firewalld 重置。
✅ 检查是否启用了 firewalld:
systemctl status firewalld
✅ 解决方案(任选一种):
systemctl stop firewalld
systemctl disable firewalld
安装 iptables 服务:
yum install -y iptables-services
systemctl enable iptables
systemctl start iptables
保存规则:
service iptables save
规则文件位置:
/etc/sysconfig/iptables
不建议混用 iptables 和 firewalld。
firewall-cmd --permanent --add-port=80/tcp
firewall-cmd --reload
CentOS 8 中:
iptables 实际是 nftables 的兼容层firewalld 或 nftables✅ 查看:
iptables -V
若看到 nf_tables,说明是兼容层。
iptables-save
只是输出规则,不会保存文件,必须重定向:
iptables-save > /etc/sysconfig/iptables
Docker 会 自动修改 iptables 规则,重启后 docker 会重新注入规则。
✅ 解决方案:
--iptables=false(不推荐)你可以按顺序检查:
cat /etc/centos-release
cat /etc/sysconfig/iptables
systemctl status firewalld
systemctl status iptables
CentOS 中 iptables 重启失效,是因为规则没有持久化,或被 firewalld / 系统初始化覆盖。
如果你愿意,可以告诉我:
我可以给你一套 完全适合你环境的解决方案。