For the complete documentation index, see llms.txt. This page is also available as Markdown.

How to set up a firewall with UFW on Ubuntu

UFW (Uncomplicated Firewall) is the easiest way to protect your VPS from unwanted traffic. It comes built into Ubuntu and takes about five minutes to configure.

Think of it as a bouncer for your server. Without a firewall, every port is open by default. With UFW, you decide exactly who gets in.

Step 1: Check if UFW is installed

UFW ships with Ubuntu by default, but let us confirm:

sudo ufw version

If you see a version number, you are good to go. If not, install it:

sudo apt update && sudo apt install ufw -y

Step 2: Set default policies

The safest approach is to deny all incoming traffic by default and allow all outgoing traffic:

sudo ufw default deny incoming
sudo ufw default allow outgoing

This way, nothing from the outside can reach your server unless you specifically allow it.

Step 3: Allow SSH (very important)

If you are connected via SSH right now, blocking port 22 would lock you out of your server. Allow SSH first:

sudo ufw allow ssh

This is the same as running sudo ufw allow 22/tcp.

Step 4: Allow other services you need

Think about what your server is going to do. Here are common rules:

Web server (HTTP and HTTPS):

Or if you prefer specifying ports:

For a specific port like a game server or custom app:

For a specific IP address only (most secure):

Step 5: Enable UFW

Double-check your rules before enabling:

If everything looks right, enable the firewall:

Type y when it asks for confirmation. UFW will start immediately and activate on every boot from now on.

Step 6: Check the status

You should see something like this:

Managing rules after setup

Delete a rule:

Block a specific IP:

Reload after making changes:

Disable UFW temporarily (not recommended for long term):

Application profiles

Some services register themselves with UFW. See what is available:

Then allow by profile name:

Rate limiting

To protect against brute force attacks on SSH, enable rate limiting:

This allows 6 connections per 30 seconds from the same IP. Any more than that gets blocked automatically.

Checking logs

If something is not working, check the firewall logs:

Common mistakes

Locking yourself out. Always allow SSH before enabling UFW. If you do get locked out, restart your VPS from the hosting panel and disable UFW from the recovery console.

Forgetting to allow a port. If a service is not working after enabling UFW, check if the port is allowed. Run sudo ufw status and look for the port. If it is missing, add it.

Allowing everything. The whole point of UFW is to restrict access. Only open the ports you actually use. Every open port is a potential entry point.

Done

Your VPS now has a basic firewall in place. It will block unwanted traffic while letting your services work normally. Not bad for five minutes of work.

Last updated