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
- Add swap space on Ubuntu 24.04Create a swap file on a small Ubuntu 24.04 VPS, make it permanent and tune swappiness so the server survives memory spikes.
- Install Docker and Compose on Ubuntu 24.04Install Docker Engine and the Compose plugin from the official repository, run it as a normal user and avoid the UFW bypass.
- Back up your server with resticEncrypted, deduplicated backups of your VPS to a server you control: install restic, run the first backup, schedule it and test a restore.
- Create an encrypted volume with LUKSKeep sensitive files in a LUKS-encrypted volume on a single-disk VPS: create, open, close, and what it does and does not protect.
