How to save iptables Rules Permanently
Instructions
Q&A (0)
Notes (0)
Resources (0)
Saving Progress...
Resources
There are no resources for this lesson.
Notes can be saved and accessed anywhere in the course. They also double as bookmarks so you can quickly review important lesson material.
Saving iptables Rules
If you're using a distribution that doesn't have iptables-persistent
or a similar tool, you can save your IP tables by using the iptables-save
to dump your config to a file, write a script to use iptables-restore
to add the rules again every time the system boots.
To have our script that we will make automatically executed, we will need to make sure the ifupdown package is installed on our system:
sudo apt install ifupdown
Installing this package ensures when we place our bash script in the /etc/network/if-pre-up.d/
directory, it will be executed automatically at boot.
Creating the backup file
Now run the following commands to save our newly created iptables rules to a file, then move that file into the /etc/iptables directory:
If the /etc/iptables directory does not exist, create it with the mkdir command
# Create the rules file
sudo iptables-save > rules.v4
# Move the file to the iptables directory
sudo mv rules.v4 /etc/iptables/rules.v4
The process of creating a backup file will need to be completed each time we update the firewall rules.
Create a Script to Load Rules on Boot:
Create a script in /etc/network/if-pre-up.d/
to load the rules when the network interface comes up:
sudo nano /etc/network/if-pre-up.d/iptables
Add the following lines to the script:
#!/bin/sh
/sbin/iptables-restore < /etc/iptables/rules.v4
Make the script executable:
sudo chmod +x /etc/network/if-pre-up.d/iptables
Now we can safely reboot our server, and when we run iptables -L
we should see our rule for port 22 still listed in the Input chain.