配置iptables后重启规则丢失,需手动持久化。先用iptables-save将规则保存至/etc/iptables/rules.v4(IPv4)和rules.v6(IPv6),创建目录并设置systemd服务开机自动restore,确保规则生效。

如果您在配置了iptables防火墙规则后重启系统,发现之前的规则丢失,这是因为iptables默认不会自动保存规则。为了确保配置的防火墙策略在系统重启后依然生效,必须手动将当前规则持久化存储。以下是几种常用的保存方法。
本文运行环境:Dell PowerEdge服务器,Ubuntu 22.04。
一、使用iptables-save和iptables-restore
该方法通过将当前运行中的iptables规则导出到文件,并在系统启动时重新加载,实现规则的持久化。
1、执行命令 sudo iptables-save > /etc/iptables/rules.v4 将现有IPv4规则保存至指定路径。
2、创建目录(如不存在)sudo mkdir -p /etc/iptables 避免保存时出现路径错误。
3、若需保存IPv6规则,运行 sudo ip6tables-save > /etc/iptables/rules.v6。
4、在系统启动时通过开机脚本或服务自动执行 iptables-restore 来恢复规则。
二、利用发行版自带的持久化工具
部分Linux发行版提供专门的工具来简化iptables规则的保存与恢复过程。
1、在Debian或Ubuntu系统中安装 iptables-persistent 软件包:sudo apt install iptables-persistent。
2、安装过程中会提示是否保存当前IPv4和IPv6规则,选择“是”即可完成初始化保存。
3、此后每次修改规则后,可通过命令 sudo netfilter-persistent save 手动保存当前规则。
4、系统启动时会自动调用 netfilter-persistent up 恢复已保存的规则。
三、编写自定义Systemd服务
当系统未提供内置持久化机制时,可创建一个Systemd服务来自定义规则加载流程。
1、将当前规则保存到文件:sudo iptables-save > /etc/iptables.rules。
2、创建服务文件 /etc/systemd/system/iptables-restore.service,写入[Unit]、[Service]和[Install]配置内容。
3、在Service部分设置执行命令为 ExecStart=/sbin/iptables-restore 。
4、启用该服务:sudo systemctl enable iptables-restore.service,确保其随系统启动而运行。










