How to Make iptables Firewall Rules Persistent on Debian/Ubuntu

Let's dive into some useful commands and see how to persist iptables rules.

Persistent iptables Firewall Rules

Here’s how to keep iptables firewall rules persistent between reboots, so you don’t lost them after the system is rebooted.

Iptables is a command-line firewall utility in Linux operating system that uses policy chains to allow or block traffic. However, by default iptables rules will not survive through a server reboot. They are reset when you reboot your Linux system. So, how do I persist iptables rules?

The iptables store the rules in the system memory. In other words, it do not save these rules persistently to the disk as a file. Fortunately, there is a very easy 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 process of installation you will be asked to save current/existing iptables rules. Select Yes or No depend on your needs.

Installing persistent-iptables Package

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 in order 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, you need to run the above command every time you make changes to iptables on your system. It basically copies the currently active iptables rules to the specified file.

The rules can also be restored back to how they were last time you saved them with:

sudo netfilter-persistent reload

You can display saved file using the cat command:

sudo cat /etc/iptables/rules.v4
Persistent iptables Saved Rules

In addition, to remove persistent iptables rules, you can simply 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.

Leave a Reply

Your email address will not be published.

Latest from Linux Knowledge