← All tutorials

Security

How to Configure Secure UFW Firewall Rules on Ubuntu 24.04

Published October 27, 2026 · 6 min read

On this page
  1. Prerequisites
  2. Step-by-Step Guide
  3. Conclusion

A server with every port open exposes services you may not know are running. UFW (Uncomplicated Firewall) is a simple front end to the Linux packet filter that lets only the traffic you choose reach the machine.

Prerequisites

Step-by-Step Guide

Step 1: Install UFW and set default policies

sudo apt update
sudo apt install -y ufw
sudo ufw default deny incoming
sudo ufw default allow outgoing

Step 2: Allow SSH before enabling the firewall

Always allow SSH first or you will lock yourself out of a remote server. The limit rule also blocks addresses that open too many connections in a short time.

sudo ufw limit 22/tcp

Step 3: Allow web traffic

sudo ufw allow 80/tcp
sudo ufw allow 443/tcp

To restrict a service to a trusted network, add a source, for example sudo ufw allow from 203.0.113.0/24 to any port 5432 proto tcp. That range is a documentation example; use your own.

Step 4: Enable logging and the firewall

sudo ufw logging low
sudo ufw enable
sudo ufw status numbered

Step 5: Review and remove rules

sudo ufw status numbered
sudo ufw delete 3

Replace 3 with the number of the rule in your own list. Blocked connections are recorded in /var/log/ufw.log.

Note: Docker publishes ports through its own iptables rules, which can bypass UFW. Bind containers to 127.0.0.1 unless a port must be public.

Conclusion

The server now drops unsolicited inbound traffic except SSH, HTTP and HTTPS. Review the rule list after every new service, remove unused rules, check the log periodically and keep packages patched with sudo apt upgrade.

Keep reading