UFW stands for Uncomplicated Firewall, and it lives up to the name — until the moment you lock yourself out of your own server. This guide shows you how to set up UFW on Ubuntu without that happening: the exact order of commands, the rules a real web server actually needs, and the five gotchas that catch experienced developers. Every command below was checked against the Ubuntu UFW wiki and current 2026 guides on 27 October 2026.
If you run a VPS, this is the single highest-value hardening step you can do in ten minutes. A default Ubuntu server accepts connections on every listening port. UFW flips that to deny-by-default, so only the services you explicitly allow are reachable from the internet.
What UFW actually does
UFW is a friendly front end for Linux’s packet filtering — historically iptables, now nftables on modern Ubuntu. You write rules like ufw allow 443/tcp and UFW translates them into the underlying firewall rules. You never touch raw iptables syntax, and your rules survive reboots once the firewall is enabled.
Two facts shape everything in this guide. First, UFW is disabled by default on Ubuntu, so a fresh server has no host firewall running at all. Second, UFW checks rules top to bottom and the first match wins, which is why rule order matters when you mix broad allows with narrow denies.
Before you touch anything: the lockout-proof checklist
Most UFW disasters follow the same script: someone enables the firewall over SSH before allowing SSH through it, and the session dies. Do these three things first.
1. Make sure you have a second way in. If your host offers a web console, serial console, or recovery shell, confirm you can reach it before you start. That console bypasses the firewall entirely and is your escape hatch.
2. Confirm what is actually listening. Only open ports for services that exist. Check with:
sudo ss -ltnp
If nothing is listening on port 22, do not blindly allow port 22 — find out which port your SSH daemon really uses first.
3. Keep your current session open. Do the whole setup in one terminal, then open a second SSH session to test before closing the first. If the second login fails, your original session is still alive and you can fix the rule.
Step 1: Install UFW and check its status
UFW ships pre-installed on most Ubuntu systems, but install it explicitly so the guide works on minimal images too:
sudo apt update
sudo apt install ufw -y
sudo ufw status verbose
On a fresh server you will see Status: inactive. That is normal and safe — it means no rules are enforced yet, so nothing you type now can cut you off. This is the whole trick: configure everything while the firewall is off, then enable it once.
Step 2: Set the default policies
sudo ufw default deny incoming
sudo ufw default allow outgoing
Deny incoming means unsolicited connections from the internet are dropped unless a rule allows them. Allow outgoing means your server can still fetch updates, call APIs, and resolve DNS. This pair is the standard baseline for a server, and every rule you add afterwards is an exception to it.
Resist the temptation to deny outgoing traffic on a first setup. It sounds stricter, but it breaks updates, package installs, NTP time sync, and outbound API calls unless you carefully allow DNS (UDP 53), HTTP (80), HTTPS (443), and NTP (123) first. Save outbound lockdown for a second pass, once the inbound rules are proven.
Step 3: Allow SSH before you enable anything
This is the step that saves your server. Add the SSH rule now, while the firewall is still inactive:
sudo ufw allow OpenSSH
OpenSSH is an application profile — a named bundle of ports that a package registers with UFW. It opens TCP port 22. If your SSH daemon runs on a custom port, allow that port explicitly instead:
sudo ufw allow 2222/tcp
If you only ever connect from one place, restrict SSH to your own address. This is the strongest simple form of the rule, and it makes brute-force attacks against your SSH port nearly irrelevant:
sudo ufw allow from 203.0.113.10 to any port 22 proto tcp
Replace 203.0.113.10 with your real public IP. Only do this if your IP is stable — if it changes, you will need the console to update the rule. For a team or an office, allow the whole subnet instead, for example 203.0.113.0/24.
Step 4: Enable UFW and verify with a second session
sudo ufw enable
sudo ufw status verbose
UFW will warn you that enabling may disrupt existing SSH connections. Since you already allowed SSH, confirm with y. The output should show Status: active with Default: deny (incoming), allow (outgoing) and your SSH rule.
Now, before you close anything, open a second SSH session. If it connects, your firewall is correct. If it does not, your first session is still open — fix the rule from there. This two-session test is the entire difference between a smooth setup and a support ticket to your hosting provider.
Step 5: Rules for the stacks you actually run
A public web server
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
Or use the Nginx profile, which opens both ports in one rule:
sudo ufw app list
sudo ufw allow "Nginx Full"
ufw app list shows every profile installed on your system — OpenSSH, Nginx, Apache, and others appear only if their packages are installed. A profile is just a convenience; it opens exactly the ports that service needs.
An app server with a private database
Never open a database port to the world. If your database lives on a second server, allow it only from the app server’s private address:
sudo ufw allow from 10.0.0.5 to any port 5432 proto tcp
sudo ufw allow from 10.0.0.0/24 to any port 3306 proto tcp
The first rule allows PostgreSQL from one host; the second allows MySQL from a private subnet. If the app and database share one server, you need no database rule at all — the app connects over localhost, which UFW does not block.
Port ranges and specific interfaces
sudo ufw allow 6000:6100/tcp
sudo ufw allow in on eth0 to any port 443 proto tcp
Port ranges suit services like passive FTP or game servers. Interface-scoped rules suit multi-homed servers: allow web traffic only on the public interface, not on the private network interface. Check your interface name with ip a — it may be ens3 or enp1s0 rather than eth0 on modern Ubuntu.
Step 6: Rate-limit SSH instead of just allowing it
A plain allow rule lets anyone hammer your SSH port forever. UFW’s limit rule is a cheap first filter: it allows connections but denies a source address after six or more connection attempts within 30 seconds.
sudo ufw limit 22/tcp
Use limit in place of allow for SSH, not alongside it — if both exist, the allow rule can match first and the limit never applies. Two honest caveats: limit counts connections, not failed logins, so it cannot tell a legitimate user from a bot, and it can throttle real users behind a shared NAT address who reconnect often. It is a filter, not a replacement for key-based login or for Fail2ban, which reads logs and bans addresses based on actual failed logins.
Step 7: Turn logging on and learn to read it
sudo ufw logging on
sudo ufw logging medium
Logging levels run from low to full. Medium is the sensible default: it records blocked packets and rate-limited connections without flooding your disk. Logs land in /var/log/ufw.log on most systems, or in syslog where that file does not exist:
sudo tail -f /var/log/ufw.log
sudo grep "UFW BLOCK" /var/log/ufw.log | tail -20
[UFW BLOCK] lines are the firewall doing its job — probes against ports you never opened. A sudden burst of blocks against one port is your cue to check whether that service should be listening at all. If the log file grows fast, drop back to logging low; do not turn logging off entirely, because then you are flying blind.
Step 8: Manage rules without making a mess
sudo ufw status numbered
sudo ufw delete 3
sudo ufw insert 1 deny from 198.51.100.0/24
status numbered lists rules with numbers so you can delete by number. Remember first-match-wins: a deny rule inserted below a broad allow rule for the same port will never fire, which is why insert 1 exists — it puts the narrow rule ahead of the broad one.
You can also delete by writing the rule again:
sudo ufw delete allow 80/tcp
For a full reset, sudo ufw reset removes every rule and disables the firewall — useful on a test box, dangerous on a remote server unless you are on the console, because it also removes your SSH rule.
Two more distinctions worth knowing. deny silently drops a packet, so a scanner sees nothing. reject sends back an ICMP “port unreachable” message, so a legitimate client fails fast instead of waiting for a timeout. Use deny for hostile traffic and reject for services you want to fail cleanly for real users.
Five gotchas that catch experienced developers
1. Docker bypasses UFW. Docker inserts its own iptables rules, so a container port published with -p 8080:80 can stay reachable even when UFW denies it. Do not assume UFW covers your containers. Bind container ports to localhost (-p 127.0.0.1:8080:80) when only the host needs them, and test reachability from outside after every deploy.
2. Your cloud firewall is a second, separate layer. AWS security groups, DigitalOcean firewalls, and Hetzner firewall rules filter traffic before it reaches your server. A port must be open in both layers to work, and closed in either layer to be blocked. When a service is unreachable, check the cloud firewall before blaming UFW.
3. IPv6 is a parallel door. UFW creates both IPv4 and IPv6 rules when IPV6=yes is set in /etc/default/ufw, which is the default. If you disable IPv6 support in UFW while your server still has an IPv6 address, services on IPv6 may end up unfiltered. Check that ufw status shows (v6) rules, and reload with sudo ufw reload after changing the setting.
4. Profiles go stale. An application profile opens the ports the package declared when it was installed. If a service changes its port later, the profile does not follow. When a rule stops working, check the real listening port with ss -ltnp rather than trusting the profile name.
5. Rules do not audit themselves. Revisit ufw status verbose after every deploy, every migration, and every incident. Stale rules for services you removed are open doors you forgot about; the fix is a quarterly five-minute review, not a bigger tool.
If you locked yourself out anyway
Do not panic and do not reboot blindly. Use your host’s web or serial console, which bypasses the firewall, and run:
sudo ufw disable
That restores access immediately. Then re-add the SSH rule, re-enable, and test with a second session before closing the console. If you have no console access at all, your remaining options are your host’s recovery mode or a support ticket — which is exactly why step one of this guide is confirming console access before you start.
The complete copy-paste setup for a web VPS
Here is the whole sequence for a typical Ubuntu web server — SSH, HTTP, HTTPS, rate-limited SSH, logging on:
sudo apt update && sudo apt install ufw -y
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw limit 22/tcp
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw logging on
sudo ufw enable
sudo ufw status verbose
Then open a second SSH session. If it connects, you are done: your server now rejects everything except SSH and web traffic, throttles SSH brute force, and logs what it blocks. Pair it with key-based SSH login and Fail2ban for the full baseline, and your VPS is dramatically harder to break into than it was ten minutes ago.
Further Reading & References
- UFW — Ubuntu Wiki (official: UFW is Ubuntu’s default firewall tool, disabled by default, default deny incoming)
- How to Use UFW on Linux Server in 2026 — YouStable (defaults, SSH-first rule, rate limiting, logging levels)
- How to Configure UFW on Linux Server — YouStable (numbered rules, delete/insert, ranges, interfaces)
- How to Set Up a Firewall on Ubuntu Server (UFW Guide) — MOSS (install, enable, reload, persistence across reboots)
- Set Up a Firewall with UFW on Ubuntu — MangoHost (application profiles, rule syntax, –force enable)
- Ubuntu: Key SSH, Web, Database Firewall Rules for UFW — LinuxSecurity (interface-scoped rules, proxy vs backend separation)
- Securing a Linux Server, Part 1: The UFW Firewall — BigMike (limit = 6 connections in 30 seconds, first-match rule order, IPv6)
- Ubuntu 24.04 VPS Security Hardening Guide — MassiveGrid (rate limiting, service rules, logging medium)
- How to Set Up Fail2ban on Ubuntu — HowToShipIt (the log-based banning layer that complements UFW’s limit rule)
- OpenSSH 10.6 Upgrade Checklist — HowToShipIt (keeping the SSH daemon behind your new firewall current)



