How to Set Up a Firewall With UFW on Ubuntu, Debian and Raspberry Pi

In short: sudo apt install ufw, then sudo ufw default deny incoming, sudo ufw allow OpenSSH and only then sudo ufw enable. Allow each service you need, ideally only from your LAN, and check with sudo ufw status verbose.

UFW (Uncomplicated Firewall) is the easiest way to control which ports on your Linux server or Raspberry Pi are reachable. Ten minutes of setup closes everything you did not mean to expose. The one rule to remember: allow SSH before you turn it on.

1. Install and Set Defaults

sudo apt update
sudo apt install ufw
sudo ufw default deny incoming
sudo ufw default allow outgoing

2. Allow SSH First

sudo ufw allow OpenSSH
# or, if OpenSSH is not listed:
sudo ufw allow 22/tcp

Even better, allow SSH only from your local network and use SSH keys instead of passwords:

sudo ufw allow from 192.168.1.0/24 to any port 22 proto tcp

3. Enable the Firewall

sudo ufw enable
sudo ufw status verbose

4. Allow Your Services

ServiceRule
Web serversudo ufw allow 80,443/tcp
Home Assistant (LAN only)sudo ufw allow from 192.168.1.0/24 to any port 8123
Pi-hole DNSsudo ufw allow 53
Samba file sharing (LAN)sudo ufw allow from 192.168.1.0/24 to any app Samba
Tailscalesudo ufw allow in on tailscale0

Not sure what your subnet is? Our CIDR notation guide explains what /24 means.

5. Delete and Manage Rules

sudo ufw status numbered
sudo ufw delete 3
sudo ufw limit OpenSSH     # rate-limit brute force attempts
sudo ufw reload

The Docker Gotcha

If you run Docker on your Pi, be careful: a port published with ports: - "8080:80" can be reachable even if UFW blocks 8080, because Docker inserts its own iptables rules. Publish on a specific address instead, for example "127.0.0.1:8080:80" or "192.168.1.50:8080:80".

Check What Is Really Open

A firewall only blocks traffic; it is still good to know what is listening. See how to check open ports on Linux, and test from another device with nmap.

Frequently Asked Questions

Will enabling UFW lock me out of SSH?

It can, if you enable it before allowing SSH. Always run sudo ufw allow OpenSSH (or allow port 22) first, then sudo ufw enable.

Does UFW work with Docker?

Not as you would expect. Docker writes its own iptables rules, so published container ports can bypass UFW. Bind ports to 127.0.0.1 or your LAN IP, or use a dedicated solution like ufw-docker.

Is UFW installed by default?

On Ubuntu yes, but disabled. On Debian and Raspberry Pi OS install it with sudo apt install ufw.

How do I allow a port only from my home network?

Use sudo ufw allow from 192.168.1.0/24 to any port 8123, replacing the subnet and port with yours.

Does UFW protect IPv6 too?

Yes, as long as IPV6=yes is set in /etc/default/ufw, which is the default.

1 thought on “How to Set Up a Firewall With UFW on Ubuntu, Debian and Raspberry Pi”

Leave a Comment