How to Configure Secure UFW Firewall Rules on Ubuntu 24.04
On this page
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
- Ubuntu 24.04 LTS with
sudoaccess - Console or out-of-band access in case a rule locks you out of SSH
- A list of the services that must be reachable (SSH, HTTP, HTTPS)
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.
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.