Overview
UFW (Uncomplicated Firewall) is the default firewall tool for Ubuntu and Debian. It provides a simple interface for managing iptables rules. This guide covers basic setup to protect your VPS.
Installing UFW
UFW is pre-installed on most Ubuntu systems. If not:
apt update
apt install ufw -y
Default Policies
Before enabling UFW, set sensible defaults:
# Deny all incoming connections by default
ufw default deny incoming
# Allow all outgoing connections
ufw default allow outgoing
Allow SSH (Critical!)
ufw allow 22/tcp
Or using the application profile:
ufw allow OpenSSH
Enable UFW
ufw enable
You will see a warning about disrupting SSH connections. Type y to proceed.
Common Rules
Web Server (HTTP/HTTPS)
ufw allow 80/tcp
ufw allow 443/tcp
Or allow both at once:
ufw allow "Nginx Full" # If using Nginx
ufw allow "Apache Full" # If using Apache
Database (MySQL/MariaDB)
Only allow from specific IPs, never expose publicly:
ufw allow from 192.168.1.100 to any port 3306
Mail Server
ufw allow 25/tcp # SMTP
ufw allow 587/tcp # SMTP submission
ufw allow 993/tcp # IMAPS
Custom Application Port
ufw allow 8080/tcp
Viewing Rules
# Show current rules
ufw status
# Show rules with numbers
ufw status numbered
# Show verbose output
ufw status verbose
Deleting Rules
# Delete by rule number
ufw status numbered
ufw delete 2
# Delete by rule specification
ufw delete allow 8080/tcp
Allowing Specific IP Addresses
# Allow all traffic from a trusted IP
ufw allow from 203.0.113.50
# Allow a specific port from a specific IP
ufw allow from 203.0.113.50 to any port 22
Blocking IP Addresses
# Block all traffic from an IP
ufw deny from 198.51.100.0
# Block a subnet
ufw deny from 198.51.100.0/24
Disabling UFW
If you need to temporarily disable the firewall:
ufw disable
Reset to Defaults
To remove all rules and start fresh:
ufw reset
Quick Reference
| Command | Description |
|---|---|
ufw enable | Enable firewall |
ufw disable | Disable firewall |
ufw status | Show current rules |
ufw allow PORT | Allow a port |
ufw deny PORT | Block a port |
ufw delete RULE | Remove a rule |
ufw reset | Reset all rules |
Locked Out?
If you accidentally blocked SSH, use the VNC Console to regain access and fix your firewall rules.