The safe order, in five commands
UFW (Uncomplicated Firewall) is the firewall tool that ships with Ubuntu. Ubuntu's server documentation calls it the default firewall configuration tool and notes that it starts out disabled. Once you enable it, the default policy denies every incoming connection, so the one thing that matters on a remote server is the order: allow SSH first, enable second, test third.
sudo ufw status verbose # 1. see where you start
sudo ufw allow OpenSSH # 2. allow SSH (port 22/tcp) before anything else
sudo ufw --dry-run enable # 3. optional: preview without applying
sudo ufw enable # 4. answer y to the SSH warning
sudo ufw status verbose # 5. confirm, then test a NEW login from a second terminal
Keep the session you are typing in open until a fresh login from another terminal works. Everything below explains each step, the variants (custom SSH port, SSH from one IP only, web ports, Docker) and what to do when something goes wrong. The commands are the same on Ubuntu 24.04 LTS, which ships ufw 0.36.2, and Ubuntu 22.04 LTS, which ships ufw 0.36.1.
Before you start: check how you are connected
Most lockouts happen because the rule you add does not match the port SSH is really using. Spend thirty seconds confirming three things first.
1. Which port is SSH listening on?
sudo ss -tlnp | grep -E 'sshd|systemd'
sudo sshd -T | grep -i '^port'
The sshd_config manual gives 22 as the default Port. If either command shows a different number, such as 2222, that is the port you must allow, not 22. The OpenSSH profile below only covers 22.
2. Is UFW already on?
sudo ufw status verbose
On a fresh Ubuntu install this prints Status: inactive. If it prints Status: active, someone (or an image script) has already enabled it; read the rules before adding more.
3. Is there another firewall in front?
Cloud and VPS providers usually filter traffic before it reaches your server. A port has to be open in every layer: the provider's firewall and UFW. When a rule looks right in UFW but traffic still does not arrive, this outer layer is the first place to look.
Step 1: set the default policies
According to the ufw(8) manual, a fresh install already uses a default incoming policy of deny, a default routed (forward) policy of deny and a default outgoing policy of allow. Setting them explicitly does no harm and documents your intent:
sudo ufw default deny incoming
sudo ufw default allow outgoing
Do not change the incoming default to reject or touch outgoing unless you have a reason. Denying outgoing traffic breaks apt, DNS and time sync until you add a rule for each.
Step 2: allow SSH (pick one form)
Ubuntu's openssh-server package installs a UFW application profile called OpenSSH that opens 22/tcp. Check it is there, then use the form that fits your setup:
sudo ufw app list
sudo ufw app info OpenSSH
| Situation | Command | What it opens |
|---|---|---|
| Standard SSH on port 22 | sudo ufw allow OpenSSH | 22/tcp from anywhere, IPv4 and IPv6 |
| Same, without the profile | sudo ufw allow 22/tcp | 22/tcp from anywhere |
| SSH moved to another port | sudo ufw allow 2222/tcp | Only the port you name |
| Only from your office or home IP | sudo ufw allow proto tcp from 203.0.113.7 to any port 22 | 22/tcp from that one address |
| Slow down password guessing | sudo ufw limit OpenSSH | 22/tcp, but blocks an IP that opens 6 or more connections in 30 seconds |
Two cautions. First, sudo ufw allow ssh also works, because UFW looks service names up in /etc/services, but it always means port 22. Second, restricting SSH to one IP is only safe if that IP is static. Many Indian home broadband and mobile connections change address, so keep a second way in (a provider console, or a bastion host with a fixed IP) before you narrow SSH down.
The limit rule comes straight from the manual: UFW allows the connection normally but denies an address that tries to start 6 or more connections within 30 seconds. It helps against brute force, but it can also catch you if a deploy tool opens many SSH sessions in a burst. Key-only login, covered in our SSH keys guide, does more for SSH security than any firewall rule.
Step 3: preview, then enable
UFW lets you add rules while it is still inactive, so the SSH rule is in place before anything is blocked. The --dry-run option prints the rules it would apply without changing anything:
sudo ufw --dry-run enable
sudo ufw enable
Over SSH, ufw enable stops and asks:
Command may disrupt existing ssh connections. Proceed with operation (y|n)? y
Firewall is active and enabled on system startup
The warning is real. The manual's remote-management section explains that enabling UFW flushes its chains, which may drop existing connections; with the SSH rule already added, port 22 is open again as soon as the firewall is up. Enabling also turns the firewall on at every boot. In scripts you can skip the prompt with sudo ufw --force enable, but only after the SSH rule has been added.
Step 4: test before you close anything
Leave your current session open. From your own computer, open a new terminal and log in again:
# Linux, macOS or Windows (OpenSSH client)
ssh -v user@203.0.113.10
# If SSH is on another port
ssh -v -p 2222 user@203.0.113.10
On Windows you can also test the TCP port alone in PowerShell. Microsoft's documentation for Test-NetConnection shows the -Port parameter and a TcpTestSucceeded result:
Test-NetConnection 203.0.113.10 -Port 22
TcpTestSucceeded : True means the firewall layers let port 22 through. If the new login fails, fix the rule from the session you still have open. If you have already lost every session, use your provider's web console; step-by-step recovery for a refused or timed-out port 22 is in SSH connection refused on port 22.
Step 5: open only what your server needs
# Web server (Nginx or Apache): HTTP and HTTPS
sudo ufw allow 80,443/tcp
# Or use the profile the web server package installs
sudo ufw allow 'Nginx Full'
# A database only your app server should reach
sudo ufw allow proto tcp from 10.10.0.5 to any port 3306
# Label rules so you remember why they exist
sudo ufw allow 8443/tcp comment 'admin panel'
The manual notes that when you list several ports they must be numeric, with no spaces, and a rule can hold at most 15 ports (a range counts as two). Never open a database port such as 3306 or 5432 to the whole internet; allow the one address that needs it. If your app listens on an internal port such as 3000 or 8000 behind Nginx, do not open that port at all.
Reading ufw status
$ sudo ufw status verbose
Status: active
Logging: on (low)
Default: deny (incoming), allow (outgoing), deny (routed)
New profiles: skip
To Action From
-- ------ ----
22/tcp (OpenSSH) ALLOW IN Anywhere
80,443/tcp ALLOW IN Anywhere
22/tcp (OpenSSH (v6)) ALLOW IN Anywhere (v6)
80,443/tcp (v6) ALLOW IN Anywhere (v6)
- To is the port (and profile) on this server; From is who may connect. The manual says
Anywheremeans any address, that is0.0.0.0/0for IPv4 and::/0for IPv6. - (v6) rows are the IPv6 copies. UFW manages IPv6 by default, so one
allowcreates both. - LIMIT in the Action column marks a rate-limited rule.
ufw statusonly lists rules you added with theufwcommand. Rules written into/etc/ufw/before.rulesand similar files do not appear;sudo ufw show rawshows the complete firewall.
To see which listening ports each rule affects, run sudo ufw show listening.
Deleting and reordering rules
UFW checks rules from the top and the first match wins, so put specific rules (deny one IP) before general ones (allow everyone). To see the order:
sudo ufw status numbered
Then delete by number or by repeating the rule with delete in front:
sudo ufw delete 3
sudo ufw delete allow 80/tcp
sudo ufw insert 1 deny from 198.51.100.23
Two details catch people. Deleting by number removes only that one line, so an IPv6 copy of the same rule stays behind; deleting by rule text removes both. And numbers shift after every delete, so run status numbered again before the next one. Before deleting anything that mentions port 22, check that another rule still allows your SSH connection.
Quick diagnosis table
| Symptom | What it usually means | Fix |
|---|---|---|
SSH hangs, then Connection timed out after enabling UFW | No allow rule matches your SSH port; the default deny drops packets silently | From the web console: sudo ufw allow 22/tcp (or your real port), or sudo ufw disable while you fix it |
Connection refused straight away | The port is open in the firewall but nothing is listening, or a reject rule matched | Check sudo ss -tlnp and systemctl status ssh; look for REJECT in ufw status |
ERROR: Could not find a profile matching 'OpenSSH' | The openssh-server package is not installed, or the profile name is misspelled | Run sudo ufw app list, or allow the port number instead: sudo ufw allow 22/tcp |
Skipping adding existing rule | The same rule is already there | Nothing to do; check with sudo ufw status |
Could not delete non-existent rule | The delete text does not exactly match an existing rule | Delete by number from sudo ufw status numbered |
Rule shows ALLOW but the site is still unreachable | A provider firewall in front of the server blocks the port | Open the same port in the provider's firewall too |
| A Docker container port is reachable even though UFW denies it | Docker sends published-port traffic through its own NAT rules before UFW's rules see it | Publish to localhost (-p 127.0.0.1:8080:80) and put a reverse proxy in front |
Status: inactive after a reboot | UFW was never enabled, or someone ran ufw disable, which also stops it starting at boot | sudo ufw enable; it then starts on every boot |
The Docker gap
Docker's documentation is blunt: Docker and UFW are incompatible by default. When you publish a container port with -p 8080:80, Docker routes that traffic in the NAT table, before it reaches the INPUT chain where UFW's rules live, so UFW never gets a say. The simplest safe pattern is to publish containers only on 127.0.0.1, which Docker's port-publishing page shows (Docker notes that before Engine 28.0, hosts on the same network segment could still reach ports published to localhost, so keep Docker current), and expose them through Nginx on 80 and 443, which UFW does control. Our guide to installing Docker on Ubuntu walks through it.
Common mistakes
- Enabling first, allowing second. Over SSH this is the classic lockout. Always add the SSH rule, then enable.
- Allowing 22 after moving SSH to another port. Allow the new port, confirm a login on it, and only then delete the port 22 rule.
- Forgetting the outer firewall. UFW and the provider firewall are separate. A port must be open in both.
- Opening a port range out of habit. Rules such as
allow 1:65535/tcpmake UFW pointless. Open single ports, and limit admin and database ports to known addresses. - Using
ufw resetto tidy up. The manual says reset disables the firewall and returns it to installation defaults, which removes your SSH rule too. If you run it, add SSH back before enabling again. - Turning logging up to
highorfull. The manual warns that levels above medium produce a lot of output and can fill a disk.low, the default, is enough for most servers; blocked packets go to the kernel log and, on systems using rsyslog, to/var/log/ufw.log. - Blocking ping for "security". The default ruleset accepts ICMP echo requests. Leaving ping on makes network problems much easier to diagnose, and blocking it does not stop a port scan from finding open ports.
- Expecting UFW to unblock outgoing email. UFW allows outgoing traffic by default, but a provider can still block a port upstream. On a Bigdomainhost VPS, outbound port 25 is closed at the network level, so send mail through an authenticated relay on port 587 instead; no UFW rule changes that.
If you are locked out
Get a shell that does not depend on SSH: your provider's web or serial console. Log in there, then either add the missing rule or switch the firewall off while you fix it:
sudo ufw status numbered
sudo ufw allow 22/tcp # or your custom port
# or, temporarily:
sudo ufw disable
ufw disable unloads the firewall and stops it starting at boot, so remember to enable it again once SSH is allowed. On a Bigdomainhost VPS the console is in the control panel, next to the panel firewall, and both are covered in the VPS documentation. If you are stuck, message us on WhatsApp at +91 75994 50220 at any time, call during IST working hours, or write to support@bigdomainhost.com.
The rest of a new server's hardening order (sudo user, key-only SSH, automatic updates, snapshots) is in our Ubuntu VPS initial setup guide.
This guide was written by the Bigdomainhost team with AI assistance; commands and behaviour were checked against the ufw(8) manual for Ubuntu 24.04, Ubuntu Server documentation, the ufw source code and Docker's documentation on 28 November 2026.
Sources (checked )
- Canonical (Ubuntu Server documentation): Firewalls: ufw (Uncomplicated Firewall)
- Ubuntu Manpages: ufw(8), Ubuntu 24.04 LTS (noble)
- Ubuntu Manpages: ufw-framework(8): rules files and evaluation order
- Launchpad (ufw project): ufw source: src/ (frontend.py, backend.py, backend_iptables.py messages and status output)
- Launchpad (Ubuntu openssh package): openssh-server.ufw.profile (the OpenSSH profile)
- Ubuntu Manpages: sshd_config(5): Port
- Docker Docs: Packet filtering and firewalls: Docker and ufw
- Docker Docs: Port publishing and mapping
- Microsoft (Internet Archive snapshot): Test-NetConnection cmdlet reference