NetPoa

Set up a firewall on Ubuntu with UFW

Updated 27 Nov 2026

A firewall closes every door on your server except the ones you choose. UFW (Uncomplicated Firewall) comes with Ubuntu and makes this simple. This guide goes further than Secure a new Cloud VPS in 10 minutes: it explains the defaults, opening and closing ports, and limiting access to your own IP.

Run these commands as a user with sudo.

1. Check UFW is installed

sudo apt update
sudo apt install -y ufw
sudo ufw status

It should say Status: inactive on a new server.

2. Set the defaults

Block everything coming in, allow everything going out:

sudo ufw default deny incoming
sudo ufw default allow outgoing

3. Allow SSH first

Allow SSH before you enable the firewall, or you will lock yourself out of the server.

sudo ufw allow OpenSSH

If you changed SSH to another port, allow that port instead, for example sudo ufw allow 2222/tcp.

4. Allow your websites

For Nginx or Apache, open HTTP (80) and HTTPS (443):

sudo ufw allow 80,443/tcp

Only open what you use. A database such as MySQL (3306) or PostgreSQL (5432) normally shouldn't be open to the internet.

5. Turn it on

sudo ufw enable

Answer y. Your current SSH session stays connected. Check the rules:

sudo ufw status verbose

Open a second SSH window and sign in to prove SSH still works before you close the first.

Allow a port only from one IP

To let only your office reach a port, such as a database or admin panel:

sudo ufw allow from 196.43.10.20 to any port 5432 proto tcp

Replace 196.43.10.20 with your office's public IP.

Remove a rule

List the rules with numbers, then delete by number:

sudo ufw status numbered
sudo ufw delete 3

Check the list again after each delete, as the numbers change.

Slow down repeated SSH attempts

limit blocks an IP that tries to connect 6 or more times in 30 seconds:

sudo ufw limit OpenSSH

For stronger protection, add Fail2ban. See Protect SSH from brute-force attacks with Fail2ban.

Using Docker?

Docker adds its own firewall rules and can bypass UFW. A container started with -p 8080:80 is open to the internet even if UFW doesn't allow 8080. Publish container ports to the local address only, like -p 127.0.0.1:8080:80, and put Nginx in front.

Locked out?

If you enabled UFW without allowing SSH, you can't reconnect. Open a ticket and choose Technical, and we'll help you get access again. As a last resort, Rebuild with a new system in the portal starts the server again from scratch, which erases everything on its disk.


Need a server? Order a Cloud VPS and get root access within minutes. For help, open a ticket and choose Technical.

Was this helpful?