Iptables is a command-line firewall utility in Linux operating system that uses policy chains to allow or block traffic.
However, iptables rules will not survive through a server reboot by default. They are reset when you reboot your Linux system. So, how do I persist with iptables rules?
The iptables store the rules in the system memory. In other words, it does not save these rules persistently to the disk as a file.
Fortunately, there is an effortless way to keep these iptables rules persistently to a disk, which I will show you now.
How to Save iptables Firewall Rules Permanently
You need to install the iptables-persistent
package, which will automatically restore iptables on reboot.
sudo apt install iptables-persistent
During the installation process, you will be asked to save current/existing iptables rules. Select Yes
or No
, depending on your needs.
If you have selected Yes
, it will create and save existing iptables rules to /etc/iptables/rules.v4
and /etc/iptables/rules.v6
for IPv4 and IPv6, respectively.
Whenever you change the rules of iptables, you should save them to the file by using the iptables-save
command to make changes persistent after reboot.
For IPv4 iptables (the most widely used scenario):
sudo iptables-save -f /etc/iptables/rules.v4
For IPv6 iptables:
sudo iptables-save -f /etc/iptables/rules.v6
Please note that you need to run the above command every time you make changes to iptables on your system. This is because it copies the currently active iptables rules to the specified file.
The rules can also be restored to how they were last time you saved them with:
sudo netfilter-persistent reload
You can display the saved file using the cat command:
sudo cat /etc/iptables/rules.v4
In addition, to remove persistent iptables rules, you can open a corresponding /etc/iptables/rules.v*
file and manually delete lines containing all unwanted rules.
Conclusion
Linux system administrators use iptables to set up, maintain and inspect the firewall rules in Linux. In this guide, you have learned how to make the iptables firewall rules persistent on your Debian or Ubuntu system.
It’s important to note that if you have ufw or firewalld commands running on your system, then iptables-persistent
will conflict with them and should be avoided.
To know more about the iptables command, you can refer to its man page or check here and here.