Installation and Basic Setup
UFW usually comes pre-installed on Ubuntu. If not, install it and set the default policies:
sudo apt install ufw sudo ufw default deny incoming sudo ufw default allow outgoing
This is the most basic and secure approach: the server can reach anything, but only explicitly allowed ports are accessible from the outside.
Allowing SSH, HTTP, HTTPS
Before enabling the firewall, make sure to open SSH — otherwise you'll lose access:
sudo ufw allow ssh sudo ufw allow http sudo ufw allow https
If you changed the SSH port to 2222:
sudo ufw allow 2222/tcp
Now it's safe to enable the firewall.
Enabling and Checking Status
Enable UFW:
sudo ufw enable
The system will warn that existing SSH connections may be disrupted — if you've already opened the SSH port, go ahead and confirm. Check the status and rule list:
sudo ufw status verbose
You'll see all active rules and the default policy. For a compact output with numbered rules:
sudo ufw status numbered
This is useful for deleting specific rules.
Adding Custom Ports
For non-standard services, open ports as needed. For example, for PostgreSQL:
sudo ufw allow 5432/tcp
For a port range (e.g., passive FTP):
sudo ufw allow 40000:50000/tcp
You can restrict access to a specific IP:
sudo ufw allow from 203.0.113.5 to any port 5432
This way only the specified address can connect to PostgreSQL. This is especially useful for databases and admin panels that shouldn't be accessible to the entire internet.
Deleting and Modifying Rules
To delete a rule, first check the rule numbers:
sudo ufw status numbered
Then delete by number:
sudo ufw delete 3
You can also delete by description:
sudo ufw delete allow 5432/tcp
To completely reset all rules:
sudo ufw reset
This will disable the firewall and remove all settings. After a reset, you'll need to set up the rules again and re-enable UFW. Be careful with reset on a remote server — make sure you have console access through your hosting panel.