Skip to content
masdzub.com
~/articles/ufw — one from the notebook

Configuring UFW Rules for a Small Linux Web Server Without Locking Yourself Out

Practical UFW rules for small Linux web servers: baseline policy, SSH rate limits, Nginx profiles, Docker bypass fixes, and real troubleshooting errors.

masdzub@website:~$ cat ~/articles/configuring-ufw-rules-for-a-small-linux-web-server.aspx.md
# 1 file · 20 min read · topic: ufw · status: published

Introduction

A working UFW ruleset for a small web server starts with four rules and one policy change: deny all incoming traffic by default, rate-limit SSH on port 22, allow 80 and 443 for HTTP traffic, and confirm that IPv6 is enabled so the default deny actually covers both stacks. Everything else on the server, meaning databases, cache daemons, admin panels, and container-published ports, should stay closed unless a specific source subnet has a written reason to reach it. The rest of this article covers how that baseline behaves under real traffic, where UFW stops working (Docker, forwarded traffic, proxies), and how to fix it when a bad rule locks you out of your own box.

What UFW actually writes to iptables

UFW is a frontend. It parses its rules from /etc/ufw/user.rules and /etc/ufw/user6.rules and translates them into iptables-save compatible output under the chains ufw-before-input, ufw-after-input, ufw-user-input, and their IPv6 counterparts. Any manual command like iptables -A INPUT -s 1.2.3.4 -j DROP will be flushed the next time you run ufw reload, because UFW rewrites the entire filter table from its own files. If a rule needs to live outside UFW’s syntax, put it in /etc/ufw/before.rules (raw *filter blocks) or /etc/ufw/after.rules, then reload.

The evaluation order matters. Traffic enters ufw-before-input first, which holds stateful -m conntrack --ctstate ESTABLISHED,RELATED accept rules and any raw rules you added to before.rules. It then passes into ufw-user-input where ufw allow and ufw deny rules sit, and finally ufw-after-input, which contains logging and reject-with-icmp rules. A common bug: adding an ACCEPT rule to before.rules for a port that is denied in ufw-user-input does not work, because the DENY in the user chain runs after the ACCEPT and terminates the packet. Put early accepts in before.rules only, and never mix the two for the same port.

ufw status verbose prints only the user chain rules, not before.rules. If your rule exists in before.rules but not in status, that is normal. To see the full picture, run iptables -S | grep -E 'ufw|DOCKER' and read the order of chains. That output is the ground truth, not the UFW status.

Baseline policy before opening a single port

Default policy lives in /etc/default/ufw. The important lines are DEFAULT_INPUT_POLICY="DROP", DEFAULT_OUTPUT_POLICY="ACCEPT", and IPV6=yes. Output accepting is fine on a small server. Inbound dropping is not, and leaving IPV6=no is the single most common cause of “I firewalled the server but IPv6 is still exposed” reports on hosted VPS instances that ship with a public IPv6 address.

Terminal window
sed -i 's/IPV6=no/IPV6=yes/' /etc/default/ufw
ufw default deny incoming
ufw default allow outgoing
ufw default deny routed

ufw default deny routed matters if you ever run Docker, libvirt, WireGuard, or a Tailscale exit node. Routed traffic is traffic going through the machine rather than to it, and under UFW’s default it is accepted unless you flip that switch. On a plain web server without forwarding, denying it costs nothing and closes a class of lateral movement bugs.

Set the policy before you add rules. ufw enable uses whatever default values were configured at the time, and flipping them afterward does not retroactively re-evaluate existing rules. On Debian this trips people up because apt install ufw does not enable the service, but ufw enable on a fresh Debian 12 box with the default file is enough. On Ubuntu Cloud images, cloud-init sometimes writes its own rules on first boot. Check /etc/ufw/user.rules before you assume it is empty.

SSH rules that survive brute-force attempts

ufw limit 22/tcp is the standard recipe. It inserts a -m limit --limit 6/min --limit-burst 6 match on new connections per source IP. Six connections per minute per IPv4 address. Break it and further attempts within the window are dropped silently, not rejected. That is deliberate: a reject gives the scanner a signal, a drop wastes its time.

The rule has two real costs. On a dual-stack host, limit counts v4 and v6 separately, which means an attacker scanning both stacks gets 12 attempts per minute instead of 6. And behind a NAT, VPN, or corporate jump host, many operators share a single source IP, so one operator hammering scp in a loop can rate-limit the rest of the team. If your team is small and the source IPs are known, skip limit and use an explicit allow from a specific range, because a hard allow from a known CIDR beats rate limiting for trusted operators.

Terminal window
ufw limit 22/tcp comment 'ssh rate limited'
ufw allow from 203.0.113.0/24 to any port 22 proto tcp comment 'office jump host'

Comments are stored in /etc/ufw/user.rules and printed by ufw status, which is worth the tiny cost because a server touched by three operators has a tendency to accumulate rules whose purpose is not obvious six months later. Any rule added before UFW 0.35 does not support comment. Check ufw --version before relying on it inside automation.

Web ports: profiles versus explicit port rules

UFW ships with an nginx profile on Ubuntu and Debian. ufw allow 'Nginx Full' opens both 80 and 443 in one command, ufw allow 'Nginx HTTP' opens 80 only, and ufw allow 'Nginx HTTPS' opens 443 only. The definition sits in /etc/ufw/applications.d/nginx. If you run Caddy, Traefik, or Apache, similar profiles exist under their package names, but they are usually installed by the distribution package, not by the web server binary itself. Verify with ufw app list before assuming a profile exists.

Terminal window
ufw allow 'Nginx Full'
# equivalent explicit form:
ufw allow 80,443/tcp

The profile is a convenience wrapper, not a different ruleset. It expands to the same explicit port rules at reload time. Use the profile when it exists so the intent is legible, use explicit ports when the profile is missing or when you need to open a nonstandard port such as 8080 for a dev environment. Do not open both the profile and the explicit ports. ufw silently skips duplicates (“Skipping adding existing rule”) but the file grows with dead entries.

One thing profiles do not cover: HTTP/3 on UDP 443. If you run Nginx or Caddy with QUIC enabled and expect HTTP/3 to work, add ufw allow 443/udp. It is a separate protocol and UFW treats it that way. Without it clients will silently fall back to HTTP/2, which looks like “QUIC does not work” rather than a firewall block, and you will lose an afternoon.

Restricting a database to one source IP

Nothing about a small web server justifies exposing PostgreSQL, MySQL, or Redis to the public internet. If a second machine needs to reach them, restrict by source. UFW accepts a from clause on any allow.

Terminal window
ufw allow from 10.20.0.0/24 to any port 5432 proto tcp comment 'app subnet to pg'
ufw allow from 10.20.0.0/24 to any port 6379 proto tcp comment 'app subnet to redis'
ufw deny 5432/tcp comment 'pg not public'
ufw deny 6379/tcp comment 'redis not public'

Order matters less than people assume here. In UFW’s generated ruleset, the DENY rules match packets that arrive from any source, but the ACCEPT rules already matched and terminated the packet before the packet reached them, so this is not the “deny first” pattern from firewall theory. It is still worth writing the deny rules because they document intent, and if someone later removes the from clause by accident, the deny is a second line of defense.

The safer approach on a small server is not to open the port at all and use a Unix socket or localhost binding. Redis with bind 127.0.0.1 on port 6379 is unreachable from anywhere else regardless of UFW state, which is a stronger guarantee. Treat UFW as the outer layer and bind addresses as the inner.

IPv6 parity is not automatic

IPV6=yes in /etc/default/ufw flips IPv6 support on, but every rule you add afterward applies to both stacks only if you write it that way. ufw allow 443/tcp covers v4 and v6 because UFW expands the rule for both. ufw allow from 203.0.113.0/24 covers IPv4 only, because a v4 CIDR cannot match a v6 address. This is intentional and correct, but it surprises operators who expect a deny incoming policy to cover both stacks and add a v4-only allow that opens a v6 hole by omission.

Verify with ufw status verbose. The output tags v6 rules with (v6). If your SSH allow shows only a v4 rule, either your v6 path is blocked upstream (common on hosted instances with a public v6 that has no route back), or you have unintentionally left 22 open on v6 through the default allow. To reach the server over v6 for managed operations, add an explicit v6 rule.

Terminal window
ufw allow from 2001:db8:1234::/48 to any port 22 proto tcp comment 'office v6'

If your hosting provider hands you a public v6 but you do not actually use it, disable it at the network layer (net.ipv6.conf.all.disable_ipv6=1 in sysctl) rather than leaving the stack running and relying on UFW alone. The default deny will hold, but there is no reason to run an unused attack surface.

The Docker port bypass problem

Docker published ports do not respect UFW rules. This is the single most common reason operators believe their firewall is working when it is not. The cause is chain order: Docker inserts its own rules into the DOCKER-USER and DOCKER chains under the FORWARD table. Traffic from the outside to a published container port enters PREROUTING, gets DNATed to the container IP, then leaves through FORWARD, which jumps into DOCKER-USER before it ever reaches ufw-before-forward. UFW rules under INPUT do not apply to forwarded traffic at all. So ufw deny 5432/tcp does nothing if Docker has -p 5432:5432 running.

The minimal fix is at the Docker level: bind published ports to loopback or to a specific interface so the packet is never eligible for DNAT from the outside.

services:
pg:
image: postgres:16
ports:
- "127.0.0.1:5432:5432"

The older approach, docker run ... -p 127.0.0.1:5432:5432 ..., is equivalent. If you genuinely need Docker to publish on the public interface and still want UFW semantics, install the third-party ufw-docker script, which inserts a jump rule into DOCKER-USER pointing back at a UFW-managed chain. It works, it is maintained, and it adds a moving part. On a small server, binding to 127.0.0.1 and letting Nginx reverse-proxy the app is simpler and does not require extra tools.

Verify the bind with ss -tlnp | grep 5432. If the listen address is 0.0.0.0:5432, UFW is irrelevant to that port. If it is 127.0.0.1:5432, Docker never DNATs from the outside and the port is effectively closed regardless of UFW state.

Logging: turning it on and reading it

ufw logging on writes to /var/log/ufw.log on Ubuntu when rsyslog or journald forwarding is set up, or to /var/log/syslog on some Debian configurations. Modern Ubuntu with journald lands the messages in journalctl -k | grep UFW and also in /var/log/ufw.log if /etc/rsyslog.d/20-ufw.conf exists. Check both before assuming logging is broken.

Terminal window
ufw logging on
ufw logging medium # default; low, medium, high, full are valid
tail -n 50 /var/log/ufw.log

Log levels are meaningful. low logs blocked packets only. medium adds allowed packets and invalid states. high adds rate-limit hits and new connections. full logs everything, which is fine for a debugging window and terrible for a production server because it fills disk under normal traffic. Run medium on a small web server. You rarely need the ACCEPT lines until you are chasing a client that says “the firewall is blocking me” and you want to prove it is not.

Reading the log takes a moment to learn. [UFW BLOCK] means dropped. [UFW AUDIT] is the audit trail. [UFW LIMIT BLOCK] is the SSH rate limit trip. The DPT=22 and SRC= fields tell you the port and source. If a scanner is hammering a port you closed and the log is filling disk, ufw logging off will stop the fire, but the correct fix is to make sure the block is at INPUT and the scanner is not also getting through a Docker DNAT path.

Editing before.rules for things UFW cannot express

Rules that need iptables syntax land in /etc/ufw/before.rules. The common ones are dropping a specific source range before any accept rule, accepting ICMP ping from anything, and logging packets that hit the default deny. The file is plain iptables-save output wrapped in *filter and COMMIT. Insert lines between the :ufw-before-input - [0:0] chain header and the COMMIT line, then ufw reload.

A block rule placed above the UFW ACCEPT rules looks like this:

-A ufw-before-input -s 198.51.100.0/24 -j DROP

Anything inside the /24 is dropped before the USB SSH or web rules can accept it. That pattern is useful for blocking a compromised subnet while you wait for provider abuse to process. It also blocks state replies for connections that were established before the block, so a DROP is harder to recover from than a temporary REJECT in that context. Prefer REJECT --reject-with icmp-port-unreachable when you want the source to know it is blocked.

ICMP ping from anywhere is another common addition, because UFW’s default denies it and monitoring tools alarm on “server is down” when it is actually “ping is blocked”.

-A ufw-before-input -p icmp --icmp-type echo-request -j ACCEPT

And a targeted log line that does not touch the default policy:

-A ufw-before-input -p tcp --dport 25 -j LOG --log-prefix "[SMTP probe] "

After any edit to before.rules or after.rules, run ufw reload. ufw status does not show these rules. Verify with iptables -S ufw-before-input.

Testing rules without losing SSH access

The single most effective protection is a scheduled unlock. Before running any command that could sever your current session, schedule a job to disable UFW in five minutes.

Terminal window
sudo bash -c 'echo "ufw disable" | at now + 5 minutes'
sudo ufw allow 22/tcp && sudo ufw reload
# confirm ssh still works from a second terminal, then kill the job:
sudo atrm <job-number>

ufw disable does not flush rules; it sets the default policy to accept for the running table until you re-enable. That is enough to recover SSH. If at is not installed, apt install at first, because the scheduled rollback is the whole point of the exercise. If you are on a host without SSH access at all (cloud console only), use the provider’s console rather than risk it.

UFW also has a dry-run mode in recent versions. ufw --dry-run <any command> prints the resulting iptables rule without applying it. Useful when you want to confirm what ufw allow proto tcp from CIDR to any port N actually translates to.

Terminal window
ufw --dry-run allow from 10.20.0.0/24 to any port 5432 proto tcp

Read the output. It shows the exact -A ufw-user-input -s 10.20.0.0/24 -p tcp --dport 5432 -j ACCEPT line that will be written. If the source or port is wrong, you catch it before enabling.

Troubleshooting with real error messages

ERROR: problem running iptables: Another app is currently holding the xtables lock. Perhaps you want to use the -w option? appears when two processes try to modify iptables at once. The usual suspects are firewalld, iptables-persistent, docker, fail2ban, or another ufw invocation from a cron. Run lsof /run/xtables.lock or ps aux | grep -E 'firewall|iptables' and stop the conflicting service. If firewalld is running, you have two firewall managers and should remove one. systemctl disable --now firewalld then ufw reload.

ERROR: Could not load logging rules almost always means the kernel module UFW needs for logging is missing or the conntrack rate-limit extension is not loaded. On a minimal container or a kernel without LOG target support, UFW cannot write its logging chain and refuses to enable. Confirm with lsmod | grep -E 'nf_log|xt_LOG|xt_limit'. On a stock Ubuntu cloud image the modules are present. If you are on a cut-down kernel (Alpine, minimal Debian in a container), install iptables and the xtables-addons package instead of trying to debug UFW in a place where it does not belong.

ERROR: initcaps\n[Errno 2] iptables: Chain already exists. means UFW tried to create a chain that is already there. Most commonly it means a previous UFW process was killed mid-reload and the chains were left behind, or firewalld is running and owns parts of the namespace. Run ufw reset (this clears all rules, so have a backup of /etc/ufw/user.rules), then ufw enable again.

ufw: command not found on RHEL, Rocky, Alma, or Fedora is expected. Those distributions ship firewalld and no UFW. Do not try to install UFW on those hosts. Use firewall-cmd with equivalent rules.

Lockout from a limit breach during a parallel rsync or git clone over SSH is the most common self-inflicted outage. The --limit-burst 6 fires after six parallel TCP handshakes in a minute. The recovery path is the cloud provider console: log in, sudo ufw disable, add ufw allow from <your-ip> above the limit rule, sudo ufw enable. If the console is not available, reboot into single-user mode and run the same commands before networking starts. Both paths are worse than scheduling at now + 5 minutes beforehand.

Firewall not enabled (skipping reload) after a restart on Debian happens because ufw is not enabled at the systemd unit level. systemctl enable ufw (the unit is ufw.service) fixes it. The ufw enable command writes persistent rules to /etc/ufw/user.rules but does not necessarily invoke systemd to enable the boot unit.

Distro and cloud provider differences

Ubuntu ships UFW enabled by default on desktop, disabled on server images, and installed. Debian ships it installed but disabled, so a fresh apt install ufw requires ufw enable before the rules take effect. Ubuntu 22.04 and 24.04 use UFW 0.36.2, which supports comment on rules. Debian 12 ships 0.36.1, which does too. Older Ubuntu 20.04 is 0.36.1 as well, and 18.04 was 0.35 with weaker comment support.

Cloud provider images usually layer a second firewall in front. DigitalOcean, Hetzner, AWS EC2, and GCP all offer network security groups or external firewalls that run before packets ever reach the machine. A rule opened in UFW that is closed in the provider console appears to not work, and the reverse is also true; an empty UFW ruleset on a host behind a provider firewall can look secure until someone removes the provider rule. Use both on a small server where the cost is low. Use the provider console as the outer layer and UFW as the inner, and document which rule lives where in a comment.

Some cloud-init scripts on first boot flush UFW entirely to enable things like k3s or kubeadm. Check /var/log/cloud-init.log if UFW rules you added do not survive a reboot, and if the box is managed by a configuration tool (Ansible, cloud-init, NixOS), put the rules there instead of hand-editing /etc/ufw/user.rules on the box.

A complete example config for a small server

A repeatable script for a 2 GB Ubuntu 24.04 VPS running Nginx, a Python app bound to 127.0.0.1:8000, and PostgreSQL bound to 127.0.0.1:5432, with one operator subnet for SSH and a monitoring host:

#!/usr/bin/env bash
set -euo pipefail
apt-get install -y ufw
sed -i 's/IPV6=no/IPV6=yes/' /etc/default/ufw
ufw --force reset
ufw default deny incoming
ufw default allow outgoing
ufw default deny routed
# SSH: operator subnet only, rate limited for everyone else
ufw allow from 203.0.113.0/24 to any port 22 proto tcp comment 'operator subnet'
ufw limit 22/tcp comment 'ssh fallback'
# HTTP
ufw allow 80/tcp comment 'http'
ufw allow 443/tcp comment 'https'
ufw allow 443/udp comment 'quic'
# Monitoring
ufw allow from 10.20.0.10 to any port 9100 proto tcp comment 'node exporter'
# Explicit denies (documentation, not the primary defense)
ufw deny 5432/tcp comment 'pg never public'
ufw deny 6379/tcp comment 'redis never public'
# Logging
ufw logging medium
ufw --force enable
systemctl enable ufw
ufw status verbose

After running it, verify from a second machine: ssh from an IP outside 203.0.113.0/24 should be rate-limited rather than denied, curl -I https://<host> should return headers, curl against http://<host>:5432 should time out. If it connects, PostgreSQL is not actually bound to loopback or Docker is publishing the port, and the UFW rules are being bypassed. ss -tlnp is the check.

Save the ruleset and diff on restore:

Terminal window
dpkg -S $(which ufw) 2>/dev/null | head -1
cp /etc/ufw/user.rules /root/user.rules.$(date +%F)
cp /etc/ufw/user6.rules /root/user6.rules.$(date +%F)

Backups, exports, and rollback

/etc/ufw/user.rules is the whole rule set (v4), /etc/ufw/user6.rules is the v6 set, and /etc/ufw/before.rules is the raw prelude. A copy of those three files is a complete backup. Restore them, then ufw reload. Do not copy /etc/ufw/after.rules unless you have customizations there, because distro updates rewrite it and eating the new version on rollback drops you back to an outdated chain layout.

If you want a human-readable export rather than the raw form, ufw status numbered plus a small awk gets you the exact ufw commands to rebuild the rules. ufw show added on some versions prints the commands, but it is not guaranteed across releases. A for loop over ufw status numbered extracting the ports and sources works, and it is what most operators script when they migrate a ruleset between servers.

ufw reset disables and flushes. ufw --force reset does not prompt. On a production server, reset is the last command you type before a gap in coverage, so pairing it with the at now + 5 minutes schedule is not paranoia. It is procedure.

Where UFW is the wrong tool

On a host pushing more than a few hundred new connections per second, UFW’s per-packet traversal of three chains plus conntrack matching starts to appear in perf top and sar as softirq time. That is not a problem for a small web server. It is a problem for a gateway or a VPN concentrator, and by the time you reach that traffic level you should be using nftables directly or a hardware device.

On servers fronted by Cloudflare or another reverse proxy, UFW sees the proxy’s IP as the source for every request. Rate limits and IP allowlists become useless at that layer, and the correct move is to enforce at the proxy (Cloudflare WAF, rate limits, IP access rules) and use UFW only to close everything that is not the proxy’s port. Anything more than that duplicates work the proxy already does, and misconfigures the piece that is easier to reason about.

For Kubernetes hosts, UFW and kube-proxy fight over the FORWARD table in the same way Docker does. The cluster has its own network policy layer. Do not run UFW on the node and expect it to be authoritative for pod traffic.

A small Linux web server with one app, one reverse proxy, and a database bound to loopback is exactly the case UFW was designed for. Four rules, an explicit operator subnet, IPv6 on, and logging at medium. Everything beyond that is either a specific requirement with a written-down reason, or a rule that will confuse the next operator.

found this useful? share it →
Written by

Dzubayyan Ahmad

System Administrator, SRE & Technical Support Engineer specialising in web hosting infrastructure — Linux servers, automation, and monitoring. Writing these notes since 2015 so future-me can find the fix again.