UFW is the usual firewall inside a Debian or Ubuntu server. Allow SSH first, set the defaults to deny incoming and allow outgoing, then enable it. On a VPS you can also use the firewall in the dashboard, which filters traffic before it reaches the server; the two work together.
Which Firewall to Use
| Firewall | Where it runs | Good for |
|---|---|---|
| Dashboard firewall | On the host, in front of the VPS | The outer layer. Easy to change from the dashboard, and Docker cannot bypass it. |
| UFW | Inside Debian and Ubuntu | Rules per service, rate-limiting SSH. |
| firewalld | Inside AlmaLinux and Rocky Linux | The same job on Red Hat style systems. |
| Windows Firewall | Inside Windows Server | Windows services and Remote Desktop. |
Without any of them, every port a service listens on is reachable from the internet. The guide UFW vs firewalld vs iptables vs nftables compares them.
Setting Up UFW
apt install -y ufw
ufw default deny incoming
ufw default allow outgoing
ufw allow OpenSSH # or: ufw allow 22/tcp
ufw enable
ufw status verbose
Allow SSH before ufw enable, or you will cut off your own session.
Common Rules
# Web server
ufw allow 80/tcp
ufw allow 443/tcp
# A custom port
ufw allow 8080/tcp
# SSH from one address only
ufw allow from 203.0.113.10 to any port 22 proto tcp
# Slow down SSH brute-force attempts
ufw limit OpenSSH
# Remove a rule
ufw status numbered
ufw delete 3
Opening port 25 inbound lets a mail server receive email, but outgoing email on port 25 is blocked on every VPS; see Sending Email From Your Server.
firewalld on AlmaLinux and Rocky Linux
firewall-cmd --permanent --add-service=ssh
firewall-cmd --permanent --add-service=http --add-service=https
firewall-cmd --reload
firewall-cmd --list-all
Docker and UFW
Docker writes its own iptables rules, so a port published with docker run -p is reachable even when UFW denies it. Use the dashboard firewall for those ports, or see UFW Not Working With Docker.
Locked Out
If a rule cuts off SSH, open the browser console, log in and run:
ufw disable
Fix the rules, allow SSH, and enable it again.