A how-to by niels.
Published: 2020-08-15 19:14:26. Updated: 2020-08-15 19:14:33.
This how-to explains how to start your firewall automatically when your Linux server boots. It does not touch on the firewall rules themselves. I'll address those in a separate how-to.
Any Linux distribution that uses systemd. (Which is almost all of them these days.)
Use your preferred text editor to create a firewall script in a suitable location. I like to create a folder called /etc/firewall:
sudo mkdir /etc/firewall
And then create a /etc/firewall/start.sh script using your preferred text editor.
The content could be something like this: (just an example - don't use as an actual firewall!)
#!/bin/bash
iptables -t nat -A POSTROUTING -s 192.168.88.0/24 -o enp1s0 -j MASQUERADE
I also have a script to stop or flush the firewall called /etc/firewall/stop.sh:
#!/bin/bash
iptables -t nat -F
Make sure the scripts are executable:
sudo chmod +x /etc/firewall/start.sh /etc/firewall/stop.sh
Create another text file named /etc/systemd/system/firewall.service with the following contents:
[Unit]
Description=System Firewall
After=network.target
[Service]
Type=oneshot
ExecStart=/etc/firewall/start.sh
RemainAfterExit=true
ExecStop=/etc/firewall/stop.sh
StandardOutput=journal
[Install]
WantedBy=multi-user.target
sudo systemctl start firewall
To have it start automatically at boot:
sudo systemctl enable firewall
sudo systemctl stop firewall