Updated 1 min read

Set up a UFW firewall on Ubuntu 24.04

Enable UFW with safe defaults, allow only the ports you use, rate-limit SSH, restrict access by IP and remove rules.

UFW is Ubuntu's simple front end to the Linux firewall. It is installed but switched off. The rule is the same as always: deny everything coming in, allow what you use.

Enable it safely#

Add the SSH rule before you turn the firewall on:

sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw limit 22/tcp
sudo ufw enable
sudo ufw status verbose

limit allows SSH but blocks an address that opens 6 or more connections in 30 seconds. If you get it wrong anyway, the console still works.

Allow what you run#

sudo ufw allow 80,443/tcp         # a website
sudo ufw allow 51820/udp          # for example a private tunnel

Allow a port only from one address (for example a database used by one other server):

sudo ufw allow from 198.51.100.7 to any port 5432 proto tcp

See and remove rules#

sudo ufw status numbered
sudo ufw delete 3

Rule numbers change after every delete: list again before the next one.

Things to know#

  • Docker bypasses UFW. Published container ports are reachable even when UFW denies them. See the Docker guide to publish on 127.0.0.1.
  • Outgoing port 25 is blocked by us, whatever UFW says (why).
  • Turn logging on with sudo ufw logging low; entries go to /var/log/ufw.log.
  • Reset everything with sudo ufw reset. This disables UFW and deletes all rules.

Back to the initial server setup.

More in this section