Guide

Firewall on a VPS with ufw

Last updated: 15 November 2026

A firewall blocks every port you did not open on purpose. The one rule that matters: allow your SSH port before you switch the firewall on. If you are logged in as root, leave out sudo.

Fast VPS from $7.99 a month

See Fast VPS plansHow ordering works

Debian and Ubuntu: ufw

  1. Install it if needed: sudo apt install ufw.
  2. Set the defaults:
    sudo ufw default deny incoming
    sudo ufw default allow outgoing
  3. Allow SSH first (use your own port if it is not 22):
    sudo ufw allow 22/tcp
  4. Allow what your services need, for example a web server:
    sudo ufw allow 80/tcp
    sudo ufw allow 443/tcp
  5. Switch it on and check:
    sudo ufw enable
    sudo ufw status verbose
    ufw warns that the command may disrupt SSH connections; answer y once your SSH port is allowed.

To remove a rule, use sudo ufw status numbered and sudo ufw delete NUMBER.

AlmaLinux and Rocky: firewalld

sudo systemctl enable --now firewalld
sudo firewall-cmd --permanent --add-service=ssh
sudo firewall-cmd --permanent --add-service=http --add-service=https
sudo firewall-cmd --reload
sudo firewall-cmd --list-all

If SSH runs on another port, also run sudo firewall-cmd --permanent --add-port=PORT/tcp before the reload, and keep your current session open until a new login works.

Good to know

Related

SSH keys on a VPS · First login · Fast VPS

Questions and answers

What is the most important firewall rule when I enable ufw?
Allow your SSH port before you run ufw enable, otherwise you lock yourself out.

Which ports should a web server leave open?
Your SSH port, 80 and 443, and nothing else unless a service needs it.

Does ufw protect ports published by Docker?
Not reliably: Docker publishes ports through its own rules. Bind private services to 127.0.0.1.

What do I do if I lock myself out?
Use the emergency VNC console on your service page, if it shows one, log in and disable or fix the rule.

Ready to try it? Fast VPS from $7.99 a month

See Fast VPS plansHow ordering works