Configure the UFW firewall without losing SSH access
Enable UFW on Debian or Ubuntu without locking yourself out of SSH: safety net, common rules, IPv6, logs and ports published by Docker.
On this page
Your values
Enter them once and the commands in this guide update.
UFW (Uncomplicated Firewall) simplifies Linux firewall management. This guide shows you how to enable it on a VPS or a dedicated server without locking yourself out, write the common rules, handle IPv6 and avoid the trap of ports published by Docker.
Prerequisites
- A server running Debian 12/13 or Ubuntu 22.04/24.04
- SSH access with
rootor asudouser - A fallback way to access the server: on a VPS, the VNC console in your client area. On a dedicated server, check the available access or contact support from your client area before you start
Step 1: identify your SSH port
From your SSH session, display the details of the current connection:
echo $SSH_CONNECTIONThe command returns four values: your IP address, your local port, the server address and the server's SSH port (the last value). Also check the configuration:
sudo sshd -T | awk '$1=="port"{print $2}'The following examples use port 22. Replace it everywhere if yours is different.
Step 2: install UFW
sudo apt update
sudo apt install ufw
sudo ufw statusAs long as you have not enabled the firewall, the status shown is Status: inactive.
Step 3: prepare the rules
Block incoming connections by default, allow outgoing ones, then open SSH before any activation:
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow 22/tcp comment 'SSH'Check the saved rules:
sudo ufw show addedThe line ufw allow 22/tcp comment 'SSH' must appear.
Step 4: enable UFW with a safety net
First schedule the automatic shutdown of the firewall in 10 minutes. If you lose access, you will only have to wait:
sudo systemd-run --on-active=10min --unit=ufw-rollback /usr/sbin/ufw disableThen enable UFW and confirm with y:
sudo ufw enable
sudo ufw status verboseWithout closing your session, open a second terminal on your computer and connect:
ssh YOUR_USER@YOUR_SERVER_IPIf the connection works, cancel the scheduled shutdown:
sudo systemctl stop ufw-rollback.timerCommon rules
| Need | Command |
|---|---|
| Website (HTTP and HTTPS) | sudo ufw allow 80,443/tcp comment 'Web' |
| HTTP/3 | sudo ufw allow 443/udp comment 'HTTP/3' |
| UDP port range | sudo ufw allow 27015:27030/udp |
| SSH from your address only | sudo ufw allow from YOUR_IP to any port 22 proto tcp |
| Database from a single address | sudo ufw allow from YOUR_IP to any port 3306 proto tcp |
| Limit repeated connections | sudo ufw limit 22/tcp |
| Block an address | sudo ufw insert 1 deny from 203.0.113.10 |
ufw limit denies an address that opens 6 or more connections within 30 seconds. Avoid it if your tools open many SSH connections in a row.
Rule order and deletion
UFW applies the first matching rule. A deny placed after a broader allow therefore has no effect: this is why the blocking example uses insert 1.
sudo ufw status numbered
sudo ufw delete allow 80,443/tcpPrefer deleting by rule text. With IPv6 enabled, sudo ufw delete 3 only removes line number 3, so only one of the two versions (IPv4 or IPv6) of the rule.
IPv6
Check that UFW handles IPv6:
grep '^IPV6' /etc/default/ufwThe expected value is IPV6=yes. If you change it, reload the firewall afterwards with sudo ufw reload. A rule without an address applies to both protocols: ufw status then shows a second line marked (v6).
UFW and Docker
Ports published by Docker bypass UFW rules: traffic is redirected to the container before it reaches the chains used by UFW. A container started with -p 8080:80 therefore remains reachable from the Internet, even without a ufw allow 8080 rule.
Recommended solution: publish on the local address
If a reverse proxy installed on the server serves the application, only expose the port locally:
services:
web:
image: nginx:1.30-alpine
ports:
- "127.0.0.1:8080:80"Restrict a published port to one address
Docker provides the DOCKER-USER chain for your own rules. Publish the port on IPv4 only ("0.0.0.0:8080:80"), then create the script /usr/local/sbin/docker-user-rules.sh:
#!/bin/sh
set -e
add_rule() {
iptables -C DOCKER-USER "$@" 2>/dev/null || iptables -A DOCKER-USER "$@"
}
add_rule -p tcp -m conntrack --ctdir ORIGINAL --ctorigdstport 8080 -s YOUR_IP -j RETURN
add_rule -p tcp -m conntrack --ctdir ORIGINAL --ctorigdstport 8080 -j DROPThe script only adds the missing rules and does not touch those of other tools, such as CrowdSec. These rules do not survive a reboot. To reload them along with Docker, create /etc/systemd/system/docker-user-rules.service:
[Unit]
Description=DOCKER-USER rules
After=docker.service
Requires=docker.service
PartOf=docker.service
[Service]
Type=oneshot
ExecStart=/usr/local/sbin/docker-user-rules.sh
RemainAfterExit=yes
[Install]
WantedBy=docker.serviceEnable everything:
sudo chmod 750 /usr/local/sbin/docker-user-rules.sh
sudo systemctl daemon-reload
sudo systemctl enable --now docker-user-rules.service
sudo iptables -S DOCKER-USERIf you later change an address or a port, delete the old rule with sudo iptables -D DOCKER-USER followed by its definition, then run sudo systemctl restart docker-user-rules again.
Check from the outside
ufw status shows neither Docker's rules nor what is actually reachable. From another machine, test the expected ports:
nmap -Pn -p 22,80,443,8080 YOUR_SERVER_IPOn the server, list the listening services:
sudo ss -tulpnLogs
sudo ufw logging low
sudo journalctl -k --no-pager | grep 'UFW BLOCK' | tail -n 20The file /var/log/ufw.log only exists if a service such as rsyslog is installed, which is not always the case on Debian. Avoid the high and full levels, which can fill the disk quickly.
Updates and backup
UFW is updated with the system (sudo apt update && sudo apt upgrade). Back up its configuration before any major change:
sudo tar czf ufw-backup.tar.gz /etc/ufw /etc/default/ufwTroubleshooting
You no longer have SSH access
If the safety net is active, wait for the delay to expire. Otherwise, open the VNC console from your client area, or contact support for a dedicated server, then run:
sudo ufw allow 22/tcp
sudo ufw reloadAs a last resort, sudo ufw disable turns off the firewall while you fix the rules.
An allowed port remains unreachable
- Check that a service is listening on this port and not only on
127.0.0.1:sudo ss -tulpn - Look for a
DENYrule placed earlier:sudo ufw status numbered - Check the protocol: a
/tcprule does not open UDP
A port closed in UFW remains accessible
It is probably published by Docker. Check with docker ps, then apply the UFW and Docker section.
Skipping adding existing rule
The rule already exists: no action is needed.
Could not load logging rules or iptables error on activation
Check that the tools are present with sudo iptables -L -n, then restart the server if the kernel has just been updated. If the error persists, contact support from your client area and include the exact message.