How to save iptables firewall rules permanently on Linux

Posted by

Limited Time Offer!

For Less Than the Cost of a Starbucks Coffee, Access All DevOpsSchool Videos on YouTube Unlimitedly.
Master DevOps, SRE, DevSecOps Skills!

Enroll Now

To save the iptables firewall rules permanently on Linux, you can use the iptables-save command to save the current rules to a file, and then use a script or systemd service to restore the rules at boot time.

Here are the steps to save iptables firewall rules permanently on Linux:

  1. First, use the iptables-save command to save the current rules to a file. You can use any file name and location, but it is recommended to use the default location for iptables rules, which is /etc/sysconfig/iptables on RedHat-based distributions and /etc/iptables/rules.v4 on Debian-based distributions.
sudo iptables-save > /etc/sysconfig/iptables    # for RedHat-based distributions
sudo iptables-save > /etc/iptables/rules.v4     # for Debian-based distributions

2. Once the rules are saved, create a script that will load the saved rules at boot time. You can use any text editor to create the script, but it is recommended to use a systemd service on newer systems. Here is an example systemd service that loads the saved iptables rules on boot:

[Unit]
Description=Load iptables rules

[Service]
Type=oneshot
ExecStart=/sbin/iptables-restore /etc/sysconfig/iptables     # for RedHat-based distributions
ExecStart=/sbin/iptables-restore /etc/iptables/rules.v4      # for Debian-based distributions

[Install]
WantedBy=multi-user.target

3. Save the script as /etc/systemd/system/iptables-restore.service and enable it with the following command:

sudo systemctl enable iptables-restore.service

4. Finally, reboot the system to verify that the saved iptables rules are loaded at boot time.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x