20 January 2019

Load your Iptables Rules Automatically After Reboot as a Systemd Service

Iptables rules are not persistent. After reboot, they are flushed. So that you don't suddenly find yourself without a firewall, the rules can be automatically reloaded with a system service.

To do this, you create a Systemd Unit that automatically loads the iptables filter rules. This way your own firewall rules are permanently applied without you having to worry about them every time.


Eine Firewall mit eigenen iptables Regeln sperrt unerwünschte Verbindungen.
A firewall with its own iptables rules blocks unwanted connections to the home network.

Create a Systemd Service to load Iptables Rules - IPv4

First you created some iptables rules with a text editor. The text file is then saved to /etc/my-iptables.rules.

# example
-A INPUT -i lo -j ACCEPT
-A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT

(This is only an example, not a complete firewall - a guide for a firewall with iptables can be found in the Arch Wiki)

Next, create a simple Systemd Unit with a text editor that loads the iptables rules:

Description = Apply my IPv4 Iptables Rules

ExecStart=/bin/sh -c "/sbin/iptables-restore < /etc/my-iptables.rules"


Save the file to /etc/systemd/system/my-iptables-rules.service.

The service must now be activated:

sudo systemctl start my-iptables-rules.service

sudo systemctl enable my-iptables-rules.service
The 2nd command "enable" restarts the service each time after reboot, and makes it persistent.

To deactivate the service, enter the following into the command line and restart the computer.

sudo systemctl disable my-iptables-rules.service

Check Status and Edit your Rules

To make sure the firewall is loaded, check the status of the service:
systemctl status my-iptables-rules.service

In case you have made a mistake, it is helpful that the line in which the error appears is indicated in the status query.

After a correction to the rules my-iptables.rules the service has to be reloaded.

sudo systemctl daemon-reload

sudo systemctl restart my-iptables-rules.service


Bei der Überprüfung des Status wird angezeigt, dass sich in Zeile 41 ein Fehler befindet. Nachdem die Iptables Regeln mit dem Texteditor nano korrigiert wurden, werden die Firewall Regeln mit Erfolg geladen.
When checking the status, it is indicated that there is an error in line 41. After correcting the iptables rules with the nano text editor, the firewall loads successfully.


To see the rules, type:

sudo iptables -L -v 


The same applies to IPv6. Here ip6tables are used. The rules are stored in a text file at /etc/my-ip6tables.rules.

The Systemd Service in this case is:

Description = Apply my IPv6 Iptables Rules

Type=oneshot ExecStart=/bin/sh -c "/sbin/ip6tables-restore < /etc/my-ip6tables.rules"


Add new comment