How to save iptables firewall rules permanently on Linux

To save iptables firewall rules permanently on Linux, you can use the iptables-save and iptables-restore commands.

  1. Start by saving your current iptables rules by running the following command:
sudo iptables-save > /etc/iptables/iptables.rules

This command will save the current iptables rules to a file named “iptables.rules” in the “/etc/iptables” directory.

  1. To make sure that the iptables rules are loaded at boot time, you can create a new script file in the “/etc/network/if-pre-up.d” directory and name it something like “iptables” with the following content:
#!/bin/sh
/sbin/iptables-restore < /etc/iptables/iptables.rules
  1. Make the script executable by running the following command:
sudo chmod +x /etc/network/if-pre-up.d/iptables
  1. Now, every time your system starts, it will automatically load the iptables rules from the “iptables.rules” file.

If you are using Ubuntu or Debian based systems, you could also use iptables-persistent package which saves the rules automatically and loads them at boot.

sudo apt-get install iptables-persistent

You can also use the iptables-apply command, which writes iptables rules to a file and reloads the rules. This command is often used for automated firewall management.

It’s important to keep in mind that these commands only save the rules for the currently running tables, if you have other tables such as the “nat” table, you should also save their rules separately.

Also, these commands will only save the rules for the current running session, any changes made after the rules have been saved will not be included in the saved file, to include them you need to repeat the process.

Leave a Comment