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.


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/ script using your preferred text editor.

The content could be something like this: (just an example - don't use as an actual firewall!)


iptables -t nat -A POSTROUTING -s -o enp1s0 -j MASQUERADE

I also have a script to stop or flush the firewall called /etc/firewall/


iptables -t nat -F

Make sure the scripts are executable:

sudo chmod +x /etc/firewall/ /etc/firewall/

Create a systemd service

Create another text file named /etc/systemd/system/firewall.service with the following contents:

Description=System Firewall



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.


Please register or login to leave a comment.