Introduction
UFW (Uncomplicated Firewall) is a user-friendly front-end for managing iptables firewall rules on Linux. It is the recommended firewall tool for Ubuntu and Debian-based servers. Configuring a firewall is one of the first security steps you should take after deploying a new VPS.
Prerequisites
- A Linux VPS with Ubuntu or Debian installed
- Root or sudo access via SSH
Installing UFW
UFW is pre-installed on most Ubuntu systems. If it is not installed:
sudo apt update
sudo apt install ufw -y
Setting default policies
Start by setting the default policies. This denies all incoming connections and allows all outgoing connections:
sudo ufw default deny incoming
sudo ufw default allow outgoing
Allowing essential services
SSH (required before enabling UFW)
Important: Always allow SSH before enabling the firewall, or you will lock yourself out.
sudo ufw allow ssh
If your SSH server runs on a custom port (e.g., 7722):
sudo ufw allow 7722/tcp
HTTP and HTTPS (web server)
sudo ufw allow http
sudo ufw allow https
Or equivalently:
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
Other common services
| Service | Command | Port |
|---|---|---|
| FTP | sudo ufw allow 21/tcp |
21 |
| SMTP | sudo ufw allow 25/tcp |
25 |
| DNS | sudo ufw allow 53 |
53 |
| MySQL | sudo ufw allow 3306/tcp |
3306 |
| PostgreSQL | sudo ufw allow 5432/tcp |
5432 |
Allowing connections from specific IPs
To allow access to a port only from a specific IP address:
sudo ufw allow from 203.0.113.50 to any port 3306
This is especially useful for database ports, which should never be open to the public.
Enabling UFW
Once your rules are configured:
sudo ufw enable
You will see a warning that existing SSH connections may be disrupted. Type y to confirm.
Checking the status
sudo ufw status verbose
This displays all active rules and the default policies.
Deleting rules
To delete a specific rule:
sudo ufw status numbered
sudo ufw delete [rule_number]
Or delete by specification:
sudo ufw delete allow 3306/tcp
Disabling UFW
To temporarily disable the firewall without removing rules:
sudo ufw disable
To reset all rules to defaults:
sudo ufw reset
Recommended minimal configuration for a web server
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow ssh
sudo ufw allow http
sudo ufw allow https
sudo ufw enable