Security

Set up a UFW firewall on Ubuntu and Debian

Set safe defaults, allow SSH before switching UFW on, open only the ports you use, limit sensitive ports to your own IP, and tidy up old rules.

BeginnerLinux server3 min read

UFW (Uncomplicated Firewall) is a friendly front end to the Linux packet filter. The idea is simple: block everything coming in, then allow only the services you actually run.

Warning: Always allow SSH before you run ufw enable. If you lock yourself out anyway, open the browser console from Open Control Panel on your service page and run sudo ufw disable.

1. Install UFW

Ubuntu includes it. On Debian install it first:

Bash
sudo apt install -y ufw

2. Set the defaults

Bash
sudo ufw default deny incoming
sudo ufw default allow outgoing

3. Allow SSH

Bash
sudo ufw allow OpenSSH

If SSH runs on another port, allow that port instead, for example sudo ufw allow 2222/tcp. To slow down password-guessing bots you can use limit instead of allow. It blocks an address that opens 6 or more connections in 30 seconds:

Bash
sudo ufw limit OpenSSH

4. Switch it on and check

Bash
sudo ufw enable
sudo ufw status verbose

Before you close your session, open a new SSH connection to prove you can still get in.

Open more ports when you need them

Bash
sudo ufw allow 80,443/tcp          # website (HTTP and HTTPS)
sudo ufw allow 'Nginx Full'        # same, using the Nginx profile
sudo ufw app list                  # profiles installed packages provide

Allow a port from one address only, for example a database used by your office IP:

Bash
sudo ufw allow from 198.51.100.7 to any port 3306 proto tcp

Remove a rule

List rules with numbers, then delete by number:

Bash
sudo ufw status numbered
sudo ufw delete 3

Numbers shift after each delete, so list them again before deleting another.

IPv6

Check that /etc/default/ufw contains IPV6=yes (the default). UFW then applies every rule to IPv6 too, so a port you did not open is closed on both.

Docker users, read this

Ports published with Docker (-p 8080:80) are handled by Docker's own rules and are reachable even if UFW does not allow them. Publish to 127.0.0.1 only (-p 127.0.0.1:8080:80) and put Nginx in front. See Install Docker and Docker Compose.

Troubleshooting

  • A service is unreachable: check sudo ufw status lists its port, and that the service listens on the public address: sudo ss -tlnp.
  • Blocked traffic: sudo ufw logging on, then watch sudo journalctl -k -f | grep UFW.
  • Start over: sudo ufw reset removes every rule and disables UFW. Allow SSH again before re-enabling.

Next steps

Was this guide helpful?

Still stuck?

Ask MdmHost AI for a quick answer, or open a ticket and our team will take a look. We are here 24/7.