UFW Firewall Basics for a New VPS
A firewall decides which ports on your server the internet can reach. On Ubuntu and Debian the friendliest tool for that is UFW — Uncomplicated Firewall.
The golden rule: allow SSH first
Turn on a firewall without allowing SSH and your current session is the last one you'll get. Always start here:
apt install -y ufw
ufw allow OpenSSH
If you moved SSH to another port, allow that port instead, e.g. ufw allow 2222/tcp.
Set sensible defaults and enable
ufw default deny incoming
ufw default allow outgoing
ufw enable
ufw status verbose
Everything inbound is now blocked except SSH.
Open what you actually use
ufw allow 80/tcp # HTTP
ufw allow 443/tcp # HTTPS
ufw allow 51820/udp # WireGuard
Allow a port only from one address — handy for a database or admin panel:
ufw allow from 203.0.113.5 to any port 5432 proto tcp
Remove a rule by its number:
ufw status numbered
ufw delete 3
The Docker gotcha
Docker writes its own firewall rules, and published container ports bypass UFW. A container started with -p 5432:5432 is reachable from the whole internet even if UFW says that port is closed.
Two simple fixes:
- Publish to localhost only: -p 127.0.0.1:5432:5432, and reach it through a reverse proxy or SSH tunnel.
- Don't publish internal services at all — let containers talk over a Docker network.
Check from the outside
From another machine, see what's really open:
nmap -Pn YOUR_SERVER_IP
Only scan servers you own.
Locked out anyway?
Use your provider's web console — it doesn't depend on SSH — and run ufw allow OpenSSH or ufw disable.
Deploy a server and firewall it in two minutes.