LinuxTutorial2 min read

How to Set Up a Firewall on Linux with UFW

Protect your Linux server with UFW (Uncomplicated Firewall) — learn to enable it, allow or deny ports, and set up sensible default rules in minutes.

Developer terminal on a laptop in low light

What Is UFW?

UFW (Uncomplicated Firewall) is a user-friendly front end for iptables, the kernel-level firewall built into Linux. Instead of writing complex iptables rules, UFW lets you allow or deny ports with simple commands. It ships with Ubuntu and most Debian-based distros.

Install UFW

sudo apt install ufw        # Debian/Ubuntu
sudo yum install ufw        # CentOS/RHEL

Step 1 — Set Default Policies

Before enabling UFW, set the default policies. The safest defaults: deny all incoming, allow all outgoing:

sudo ufw default deny incoming
sudo ufw default allow outgoing

Step 2 — Allow SSH Before Enabling

Critical: Always allow SSH before enabling the firewall, or you will lock yourself out of a remote server:

sudo ufw allow ssh          # allows port 22
# or be explicit:
sudo ufw allow 22/tcp

Step 3 — Enable UFW

sudo ufw enable

You'll see: "Command may disrupt existing ssh connections. Proceed with operation (y|n)?" — type y.

Common Rules

sudo ufw allow 80/tcp           # HTTP
sudo ufw allow 443/tcp          # HTTPS
sudo ufw allow 3000             # custom app port
sudo ufw allow from 192.168.1.0/24   # allow entire local network
sudo ufw deny 8080              # block a port

Allow by application profile

sudo ufw app list               # see available profiles
sudo ufw allow 'Nginx Full'     # HTTP + HTTPS for Nginx
sudo ufw allow 'OpenSSH'

Remove Rules

sudo ufw delete allow 3000
sudo ufw delete allow 'Nginx Full'

Or by rule number (shown in ufw status numbered):

sudo ufw status numbered
sudo ufw delete 3

Check the Current Status

sudo ufw status            # enabled/disabled + rule list
sudo ufw status verbose    # more details including default policies

Disable or Reset

sudo ufw disable           # turn off without deleting rules
sudo ufw reset             # delete all rules and start fresh

Recommended Starter Config for a Web Server

sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow ssh
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw enable
sudo ufw status verbose