Last updated

Security

UFW Firewall on Ubuntu 24.04 and 22.04: Quick Command Reference

UFW (Uncomplicated Firewall) is the simple front end for the Linux firewall on Ubuntu. This page is the quick reference: the safe order to switch it on, and the commands you will use every week. It works the same on Ubuntu 24.04, 22.04 and 20.04.

Related guide: Full firewall setup guide: UFW, iptables, rate limiting and nftables

1. Check the status

UFW is installed on Ubuntu by default but switched off. If it is missing, install it with sudo apt install ufw.

sudo ufw status verbose

2. Set safe defaults

Block everything coming in, allow everything going out. Nothing changes until UFW is enabled.

sudo ufw default deny incoming
sudo ufw default allow outgoing

3. Allow SSH before you enable it

Do this first or you can lock yourself out of a remote server. OpenSSH is the application profile for port 22; if SSH runs on another port, allow that port instead.

sudo ufw allow OpenSSH
# or, for a custom port:
sudo ufw allow 2222/tcp

4. Turn it on

Type y when it warns that existing SSH connections may be disrupted. Your SSH rule from step 3 keeps you connected.

sudo ufw enable

5. Open web and other ports

Allow only what the server actually serves. App profiles like Nginx Full (80 and 443) come from installed packages; list them with sudo ufw app list.

sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw allow 'Nginx Full'

6. Everyday commands

Keep this table handy. Numbered rules make deleting the right one easy.

CommandWhat it does
sudo ufw status numberedList rules with numbers
sudo ufw delete 3Delete rule number 3
sudo ufw allow from 203.0.113.5Allow everything from one IP address
sudo ufw allow from 203.0.113.5 to any port 22Allow SSH from one IP address only
sudo ufw deny 3306Block the MySQL port
sudo ufw limit OpenSSHRate limit SSH (blocks repeated connection attempts)
sudo ufw app listShow application profiles
sudo ufw logging onLog blocked connections to /var/log/ufw.log
sudo ufw reloadReload rules after editing config files
sudo ufw disableTurn the firewall off (rules are kept)
sudo ufw resetRemove every rule and turn UFW off

FAQ

Will enabling UFW disconnect my SSH session?

Not if you allow SSH first (step 3). UFW keeps existing connections that match an allow rule, so add sudo ufw allow OpenSSH before sudo ufw enable.

Does UFW work with Docker?

Not on its own. Docker writes its own iptables rules, so ports published with -p can be reachable even when UFW denies them. Bind containers to 127.0.0.1 or filter in the DOCKER-USER chain.

Is UFW the same on Ubuntu 24.04 and 22.04?

Yes. The commands are identical; newer releases use nftables underneath, which UFW handles for you.