Linux防火墙规则默认运行时生效、重启丢失,firewalld需加--permanent后reload并enable服务,iptables需iptables-save保存至系统路径并配置开机restore,二者不可共存。

Linux 防火墙规则默认是运行时生效的,重启后会丢失。要让配置持久化,关键不是“保存状态”,而是保存规则并确保开机自动加载。不同防火墙工具(firewalld vs iptables)处理方式不同,不能混用。
firewalld:推荐用于 CentOS 7+/RHEL 8+/Ubuntu 20.04+
firewalld 是现代主流发行版默认的防火墙管理器,规则自带持久化机制,只需启用服务并正确添加永久规则:
- 添加端口或服务时务必加 --permanent 参数,例如:
firewall-cmd --permanent --add-port=8080/tcp - 添加后必须执行
firewall-cmd --reload才能生效(不中断连接) - 设置开机自启:
systemctl enable firewalld - 验证是否启用自启:
systemctl is-enabled firewalld(返回 enabled 即成功) - 重启后检查规则是否还在:
firewall-cmd --list-ports和firewall-cmd --list-services
iptables:适用于旧系统或手动精细控制场景
iptables 本身不保存规则,需配合 iptables-save 和 iptables-restore 实现持久化:
- 将当前规则保存到文件(如
/etc/sysconfig/iptables):iptables-save > /etc/sysconfig/iptables - 开机时自动恢复:依赖
iptables-services包(CentOS/RHEL)或通过/etc/rc.d/rc.local调用iptables-restore < /etc/sysconfig/iptables - Ubuntu/Debian 系统通常不预装该服务,建议改用
netfilter-persistent:sudo apt install iptables-persistent→ 保存时会自动提示存入/etc/iptables/rules.v4 - 注意:不要同时启用 firewalld 和 iptables 服务,二者冲突
验证与排错要点
规则写对了,但重启后没生效?常见原因有:
- 忘记加 --permanent(firewalld)或未执行
iptables-save(iptables) - 服务未设为开机自启:
systemctl enable firewalld或对应 iptables 服务名 - 配置文件路径错误(如把规则写进
/tmp/或用户家目录,重启即清空) - SELinux 或 systemd 限制了 rc.local 执行权限(需
chmod +x /etc/rc.d/rc.local并systemctl enable rc-local) - 使用了图形界面环境,某些桌面管理器可能覆盖网络策略
一句话总结操作逻辑
firewalld:先永久添加 → 再 reload → 最后 enable 服务;
iptables:先 save 到系统级路径 → 再配开机 restore → 最后确保服务或脚本被调用。两者都依赖服务管理器(systemd)完成启动阶段加载,不是靠“记住上次状态”。


















