Automatically start firewall on Ubuntu

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.

Requirements

Any Linux distribution that uses systemd. (Which is almost all of them these days.)

Create a firewall script

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 a systemd service

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

Start the firewall

sudo systemctl start firewall

To have it start automatically at boot:

sudo systemctl enable firewall

Stop the firewall

sudo systemctl stop firewall
Tags: ubuntu
Please login to watch this page.

Comments

Please register or login to leave a comment.

Toast