How to permanently enable iptables rules

How to permanently enable iptables rules

iptables rules are all lost when the PC is shutdown. This post shows how to permanently enable the added rules even after restarts. The post uses systemctl startup script introduced here.

Suppose that you want to add this rule: -A INPUT -i docker0 -j ACCEPT -p tcp --dport 1234.

Step 1: add systemctl service file

Create file /etc/systemd/system/iptables-rules.service with the following content

[Unit]
Description=Add iptables rules

[Service]
ExecStart=iptables -A INPUT -i docker0 -j ACCEPT -p tcp --dport 1234
ExecStop=iptables -D INPUT -i docker0 -j ACCEPT -p tcp --dport 1234
RemainAfterExit=yes

[Install]
WantedBy=multi-user.target

Note: you can use any name other than iptables-rules, which will be the service name.

Step 2: start and enable the service

systemctl enable --now iptables-rules

Step 3: checking

Check the service with

systemctl status iptables-rules

and

iptables -L INPUT -v
Buy Me A Coffee