UFW (Uncomplicated Firewall) is the standard firewall front-end on Ubuntu and Debian. A correctly configured firewall is one of the most important steps after deploying any new VPS — it ensures only the services you intend to expose are reachable from the internet.
Prerequisites
- Ubuntu or Debian VPS
- Root or sudo access
- SSH access to the server
Step 1 — Install UFW
sudo apt update
sudo apt install ufw -y
Step 2 — Set Default Policies
sudo ufw default deny incoming
sudo ufw default allow outgoing
Step 3 — Allow SSH BEFORE Enabling UFW
This step is critical — skipping it will lock you out.
sudo ufw allow OpenSSH
If you use a custom SSH port:
sudo ufw allow 2222/tcp
Step 4 — Allow Web Traffic (if applicable)
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
Or use an application profile:
sudo ufw allow 'Nginx Full'
Step 5 — Enable UFW
sudo ufw enable
Confirm with y when prompted.
Step 6 — Review Active Rules
sudo ufw status numbered
Allowing Access From a Specific IP Only
For admin panels or databases that shouldn't be public:
sudo ufw allow from 203.0.113.10 to any port 2222 proto tcp
Deleting a Rule
sudo ufw status numbered
sudo ufw delete 3
Rate-Limiting SSH
UFW can automatically throttle repeated connection attempts:
sudo ufw limit OpenSSH
Common Ports Reference
| Port | Service |
|---|---|
| 22 | SSH (default) |
| 80 / 443 | HTTP / HTTPS |
| 25 / 587 / 465 | SMTP |
| 3306 | MySQL/MariaDB |
| 5432 | PostgreSQL |
Never open database ports (3306, 5432, 6379...) to the public internet unless absolutely required — restrict them to specific IPs instead.
Common Errors
Lost SSH access after enabling UFW — the SSH rule was not added first. Use your provider's console to log in and fix the rules.
Website unreachable — verify ports 80/443 are allowed: sudo ufw status.
Best Practices
- Deny by default, allow explicitly — never the reverse
- Combine UFW with Fail2Ban for dynamic protection
- Review firewall rules after installing any new service
FAQ
Does UFW replace iptables?
No, UFW is a simplified front-end that manages iptables/nftables rules for you.
Can I allow only specific countries or IP ranges?
Yes, using CIDR notation in ufw allow from rules, though for country-level blocking a dedicated tool like GeoIP with iptables is more appropriate.
Continue Reading
- SSH Hardening: Change the Port, Disable Root Login & Use SSH Keys
- How to Install and Configure Fail2Ban
- VPS Security Checklist for Beginners
Browse more articles in Server Security & Hardening.
