A firewall is one of the first things you should configure on any new Linux server. UFW (Uncomplicated Firewall) is the standard, beginner-friendly tool for managing firewall rules on Ubuntu and Debian-based systems. It provides a simple command-line interface for controlling which traffic can reach your server. Here is how to set it up correctly from scratch.
Step 1: Install UFW
UFW comes pre-installed on most Ubuntu systems. If you are on a minimal Debian installation, you may need to install it first:
sudo apt update
sudo apt install ufw
Step 2: Allow SSH Before Enabling the Firewall
This is the most important step. If you enable UFW before allowing SSH, you will immediately be locked out of your remote server with no way back in. Run this command first:
sudo ufw allow ssh
This is equivalent to sudo ufw allow 22/tcp. If your SSH server runs on a non-standard port, replace 22 with your actual port number.
Step 3: Set Default Policies
The standard and most secure default policy is to deny all incoming connections while allowing all outgoing connections:
sudo ufw default deny incoming
sudo ufw default allow outgoing
Step 4: Allow the Services You Need
Now add rules for any services you want accessible from the internet. Common examples include:
# Allow web traffic
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
# Allow a specific IP address only
sudo ufw allow from 203.0.113.10
Step 5: Enable UFW
Once you have configured your rules, enable the firewall:
sudo ufw enable
You can verify the current status and active rules at any time with:
sudo ufw status verbose
How to Delete a Rule
To remove a rule, first list all active rules with their reference numbers, then delete by number:
sudo ufw status numbered
sudo ufw delete 3
Replace 3 with the actual number of the rule you want to remove. After deleting, confirm the remaining rules look correct with sudo ufw status verbose.