Talk to the NOC, IST hours — +91 75994 50220 support@bigdomainhost.com
Guide

How to set up UFW on Ubuntu without locking yourself out

UFW is the simple firewall built into Ubuntu, and one wrong order of commands can cut off the SSH session you are using to set it up. This guide gives the safe sequence for Ubuntu 24.04 and 22.04, explains every SSH rule variant, how to read ufw status, how to delete rules, and how to recover if you do get locked out.

Short answer: To set up UFW on Ubuntu without locking yourself out, allow SSH first with sudo ufw allow OpenSSH (or your custom SSH port), then run sudo ufw enable and check sudo ufw status verbose. UFW denies all incoming connections once enabled, so test a new SSH login from a second terminal before closing your current one.

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
Ways to allow SSH in UFW
SituationCommandWhat it opens
Standard SSH on port 22sudo ufw allow OpenSSH22/tcp from anywhere, IPv4 and IPv6
Same, without the profilesudo ufw allow 22/tcp22/tcp from anywhere
SSH moved to another portsudo ufw allow 2222/tcpOnly the port you name
Only from your office or home IPsudo ufw allow proto tcp from 203.0.113.7 to any port 2222/tcp from that one address
Slow down password guessingsudo ufw limit OpenSSH22/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 Anywhere means any address, that is 0.0.0.0/0 for IPv4 and ::/0 for IPv6.
  • (v6) rows are the IPv6 copies. UFW manages IPv6 by default, so one allow creates both.
  • LIMIT in the Action column marks a rate-limited rule.
  • ufw status only lists rules you added with the ufw command. Rules written into /etc/ufw/before.rules and similar files do not appear; sudo ufw show raw shows 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

Common UFW symptoms, what they mean and the fix
SymptomWhat it usually meansFix
SSH hangs, then Connection timed out after enabling UFWNo allow rule matches your SSH port; the default deny drops packets silentlyFrom the web console: sudo ufw allow 22/tcp (or your real port), or sudo ufw disable while you fix it
Connection refused straight awayThe port is open in the firewall but nothing is listening, or a reject rule matchedCheck 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 misspelledRun sudo ufw app list, or allow the port number instead: sudo ufw allow 22/tcp
Skipping adding existing ruleThe same rule is already thereNothing to do; check with sudo ufw status
Could not delete non-existent ruleThe delete text does not exactly match an existing ruleDelete by number from sudo ufw status numbered
Rule shows ALLOW but the site is still unreachableA provider firewall in front of the server blocks the portOpen the same port in the provider's firewall too
A Docker container port is reachable even though UFW denies itDocker sends published-port traffic through its own NAT rules before UFW's rules see itPublish to localhost (-p 127.0.0.1:8080:80) and put a reverse proxy in front
Status: inactive after a rebootUFW was never enabled, or someone ran ufw disable, which also stops it starting at bootsudo 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/tcp make UFW pointless. Open single ports, and limit admin and database ports to known addresses.
  • Using ufw reset to 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 high or full. 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 )

Answers

Frequently asked questions

Still unsure? Call +91 75994 50220 or write to support@bigdomainhost.com — a human replies in IST hours.

How do I allow SSH in UFW?

Run sudo ufw allow OpenSSH, which uses the profile installed by Ubuntu's openssh-server package and opens port 22/tcp. If SSH listens on another port, allow that port instead, for example sudo ufw allow 2222/tcp. Add the rule before you run sudo ufw enable, then confirm it with sudo ufw status.

Will ufw enable disconnect my SSH session?

It can. Enabling UFW flushes its chains, which may drop existing connections, and the default policy then denies all incoming traffic. If an SSH rule is already in place, port 22 is open again as soon as the firewall is up. UFW warns you with a y/n prompt when you enable it over SSH.

How do I check if UFW is enabled?

Run sudo ufw status. It prints Status: inactive when the firewall is off and Status: active followed by your rules when it is on. sudo ufw status verbose also shows the default policies and logging level, and sudo ufw status numbered shows rule numbers for deleting.

Is UFW enabled by default on Ubuntu?

No. UFW is installed on Ubuntu but disabled until you run sudo ufw enable. Its installation defaults are deny incoming, deny routed and allow outgoing, and those take effect only once it is enabled. After that, UFW starts automatically at every boot.

How do I delete a UFW rule?

Either repeat the rule with delete in front, such as sudo ufw delete allow 80/tcp, or list rules with sudo ufw status numbered and run sudo ufw delete followed by the number. Deleting by number removes only that line, so an IPv6 copy may remain; deleting by rule text removes both.

What does ufw limit do?

ufw limit allows connections to a port but denies an IP address that tries to open 6 or more connections within 30 seconds. It is meant to slow brute-force login attempts on SSH, for example sudo ufw limit OpenSSH. It is not a substitute for key-only SSH login.

Why does Docker bypass UFW?

Docker routes traffic for published container ports through its own NAT rules, before it reaches the INPUT chain that UFW filters. A port published with -p 8080:80 can therefore be reachable even when UFW denies it. Publish containers on 127.0.0.1 and expose them through a reverse proxy instead.

How do I get back in if UFW locked me out?

Use a console that does not depend on SSH, such as your VPS provider's web console. Log in there, add the missing rule with sudo ufw allow 22/tcp or your custom port, or run sudo ufw disable while you fix it, then enable the firewall again and test a new SSH login.

Support that picks up the phone.

In IST hours, in Hindi or English, and WhatsApp replies fastest at any time. Sales, migration and emergencies all reach the same engineers. No offshore queue, no 48-hour first reply.

Need cPanel or WHM with the ports already sorted?

Web & cPanel hosting comes with cPanel ready to log in to, reseller hosting adds white-label WHM, and a KVM VPS can have cPanel & WHM pre-installed. Call +91 75994 50220 or email support@bigdomainhost.com.