Setting up ufw firewall rules vps owners can trust starts with one habit: allow SSH before you switch the firewall on. UFW, short for Uncomplicated Firewall, is the front end for iptables that ships with Ubuntu. It does exactly what you tell it to do, and that includes blocking your own SSH session if you enable it before adding an allow rule. This guide walks through a setup order that keeps you connected, shows the exact commands, and covers how to get back in if something still goes wrong.
Why Most People Lock Themselves Out
UFW ships inactive on a fresh Ubuntu install. The moment you run ufw enable, its default policy takes effect: deny all incoming traffic, allow all outgoing traffic. That policy is right for a server, but it is also the trap. If no rule allows port 22, the firewall drops your SSH connection the second it starts, and every new attempt after that gets dropped too. Your server keeps running, your sites stay up, but you cannot log in.
The command looks harmless, and UFW’s warning is easy to skim past on a remote server. The fix never changes: add the SSH allow rule first, check it, then enable the firewall.
Before You Enable Anything: A Short Checklist
Run through this list while you still have a working SSH session. Each item is your way back in if a rule goes wrong.
- Know your SSH port. The default is 22. If you moved it, allow the custom port instead. Not sure? Check with
grep Port /etc/ssh/sshd_configbefore you touch UFW. - Keep your current session open. Log in from a second terminal window before you enable UFW, so one session stays live if new logins get blocked.
- Know how to reach the provider console. Hetzner, DigitalOcean, Vultr, Linode, and Contabo all offer a web console or VNC access that bypasses SSH entirely. Find that page now and confirm you can log in. That console is your recovery path, and our checklist of the first things to do after buying a VPS covers it as part of the initial setup.
- Confirm UFW is installed. Check with
sudo ufw status. If the command is missing, install it withsudo apt install ufw.
Step by Step: A Safe UFW Firewall Rules VPS Setup
Follow these steps in order. The ufw allow ssh step comes first for a reason: it is the only rule standing between you and a locked server.
Step 1: Set the default policies. Deny incoming traffic by default and allow outgoing traffic so the server can still reach update servers and APIs.
sudo ufw default deny incoming sudo ufw default allow outgoing
Step 2: Allow SSH. Use the service name on the default port, or the port number if you moved SSH. The service name is clearer and less error-prone.
sudo ufw allow OpenSSH
If SSH listens on a custom port, say 2222, allow that port instead:
sudo ufw allow 2222/tcp
If you want to change the port later, read our guide on how to change the default SSH port safely, and update the UFW rule to match before you restart SSH.
Step 3: Check the rules before enabling. Look at the list and confirm SSH is there.
sudo ufw show added
You should see the SSH rule in the output. If it is missing, stop here and add it. Do not run the next command until the rule shows up.
Step 4: Enable UFW. UFW will warn you that enabling may break your SSH connection. That warning is why you added the rule first. Answer yes.
sudo ufw enable
Use sudo ufw --force enable only in scripts or automated setups, and only after confirming the SSH rule is in place. The --force flag skips the warning, which also skips your last chance to catch a missing rule.
Step 5: Verify from a new session. Log in again from a new terminal window. If it works, your rules are correct. Then check the live status:
sudo ufw status verbose
The output lists the default policies and every active rule.
Allow Only What You Need: Web, Mail, and App Ports
A firewall works best when it allows the smallest set of ports your server actually uses. Open a port only when a service needs it, and close it again when the service goes away. For a typical web server, HTTP and HTTPS come next:
sudo ufw allow 80/tcp sudo ufw allow 443/tcp
Or combine them into one command:
sudo ufw allow 80,443/tcp
Add other services the same way, one at a time. A mail server needs ports 25, 587, and 993 depending on what it runs, and a WireGuard VPN needs its UDP port, usually 51820. A database such as MySQL or PostgreSQL should almost never be open to the whole internet. If only your app server needs it, allow just that IP address:
sudo ufw allow from 203.0.113.10 to any port 3306
Replace the IP with the real address of the server that needs access. Rules tied to a single source IP are far safer than opening a database port to everyone. For more detail on port choices, see our guide on how to configure UFW firewall rules for a web server step by step.
Rate-Limit SSH to Slow Down Brute Force
An open SSH port attracts password guessing bots within minutes of going live. UFW has a built-in rate limit that blocks an IP after too many connection attempts in a short window. Replace the plain allow rule with a limit rule:
sudo ufw limit OpenSSH
Or, if you run SSH on a custom port:
sudo ufw limit 2222/tcp
Rate limiting is one layer, not the whole answer. Key-only login removes password guessing entirely, and fail2ban adds automatic bans for repeat offenders. Our guide on how to harden SSH with key-only login and fail2ban walks through both.
How to Recover If You Get Locked Out Anyway
Mistakes still happen: a wrong port number, a rule deleted by accident, or a config change that moved SSH to a different port. Here is how to get back in.
Use the provider console. Log in to your VPS provider dashboard and open the web console or VNC session. That gives you a local terminal on the server that does not go through the firewall. From there, check the rules with sudo ufw status verbose and fix the missing SSH rule.
Disable UFW from the console to restore access fast. If the rules are a mess, turn the firewall off, log in over SSH, fix the rules, and enable it again:
sudo ufw disable
Reset and start over when the rules are beyond repair. The ufw reset command wipes every rule and returns UFW to its inactive, default state. Run it from the console, not over SSH, since it asks for confirmation.
sudo ufw reset
After a reset, repeat the setup from the start: default policies, allow SSH, check, then enable. A reset is the clean way back to a known good state, and it beats guessing which rule broke your login.
Check SSH itself before blaming the firewall. If the console works but SSH still refuses connections after you disable UFW, the problem is SSH, not the firewall. Check the service with sudo systemctl status ssh and read the recent log with sudo journalctl -u ssh --no-pager -n 50.
Common Mistakes Worth Avoiding
- Enabling UFW before allowing SSH. The classic lockout.
- Allowing port 22 after moving SSH to another port. The rule must match the port SSH actually listens on, so check the config, not your memory.
- Using
ufw --force enableon a first setup. Skip it except in automation you have already tested. - Opening database ports to the world. MySQL on 3306 and PostgreSQL on 5432 should be reachable only from specific IPs, or not at all from outside.
- Forgetting IPv6. UFW manages IPv4 and IPv6 rules together by default. If you disabled IPv6 in
/etc/default/ufw, your rules apply to IPv4 only. - Never reviewing the rules. A port you opened for a test six months ago is still open today unless you removed it.
A Five-Minute Monthly Check
Once a month, run sudo ufw status numbered and read the list. Delete rules you no longer need with sudo ufw delete 3, using the number shown in the list. Confirm the SSH rule is still there and still points at the right port.
Pair it with the rest of your server routine: apply pending security updates, check failed SSH logins, and confirm your backups still restore. A firewall is one part of server security, but it is the part that decides who even gets to knock on the door.
On a fresh server, this UFW setup fits into the first hour of work. Our full UFW setup walkthrough for Ubuntu 24.04 covers the same ground with more detail on application profiles and IPv6.