Web servers and networking · Intermediate · 16 min
Go further with UFW: app profiles, rate limits and logging
By Padding · Updated 18 Nov 2026
Ubuntu 26.04.1 LTS · UFW 0.36.2
You will preview UFW changes with a dry run, give a two-port app its own profile, open ports to one subnet only, see exactly what the SSH limit rule counts, put rules in the right order, read blocked-packet logs and add a rule the ufw command cannot write.
On this page
The first UFW tutorial got you to a working firewall: deny by default, SSH and web ports open. That is enough for a single website. It stops being enough when you run an app on more than one port, want a port reachable only from your private network, need to block a noisy range above an existing allow, or have to explain to someone why a connection was refused.
This tutorial works through those jobs on Ubuntu 26.04 with UFW 0.36.2. Every change is previewed first with ufw --dry-run, which prints the rules UFW would write and changes nothing. The examples use an app called Invoicer that listens on ports 8080 and 8081, a private subnet 10.20.0.0/24 and documentation addresses such as 203.0.113.0/24. Replace them with your own as you go.
Step 1 · Preview a rule before you add it
Any UFW command can be run with --dry-run straight after ufw. UFW then prints the iptables rules file it would write, and touches neither the file nor the running firewall:
sudo ufw --dry-run allow 8080/tcpThe output is long, because UFW prints the whole rules file with your existing rules in it. Near the end you will find the new rule as a pair of lines, something like:
### tuple ### allow tcp 8080 0.0.0.0/0 any 0.0.0.0/0 in
-A ufw-user-input -p tcp --dport 8080 -j ACCEPTThe ### tuple ### comment is how UFW stores the rule you typed. The -A ufw-user-input line is the iptables rule the kernel will enforce. A second block follows for IPv6, and the run ends with Rules updated or Rule added, even though nothing was saved.
Check it worked
Filter the dry run down to the rule itself:
sudo ufw --dry-run allow 8080/tcp | grep -- '--dport 8080'You see the -A ufw-user-input -p tcp --dport 8080 -j ACCEPT line, once for IPv4 and once for IPv6 (ufw6-user-input, if IPv6 is on). Then run sudo ufw status and confirm that 8080 is not listed: the preview really did change nothing.
Step 2 · Give a two-port app its own profile
An application profile is a small INI file in /etc/ufw/applications.d/ that names a set of ports. Rules that use the profile name stay readable, and if the app's ports change you edit one file instead of hunting down rules.
Create a profile for Invoicer, which serves its API on 8080 and an admin dashboard on 8081:
sudo tee /etc/ufw/applications.d/invoicer > /dev/null <<'EOF'
[Invoicer]
title=Invoicer web app
description=Invoicer API on port 8080 and admin dashboard on port 8081
ports=8080,8081/tcp
EOFThe section name in square brackets is the profile name you use in rules. ports takes the same forms as a rule: a single port (8080/tcp), a comma list with one protocol (8080,8081/tcp), a range (60000:61000/udp), or several groups joined with | (8080/tcp|5353/udp). Keep it owned by root and not writable by other users; UFW warns about files it considers insecure. sudo tee creates it that way.
Ask UFW what it found:
sudo ufw app list
sudo ufw app info InvoicerCheck it worked
ufw app list includes Invoicer next to OpenSSH. ufw app info Invoicer prints the title, the description and a Ports: heading with 8080,8081/tcp under it. If the profile is missing, check that the file is at /etc/ufw/applications.d/invoicer and that ls -l /etc/ufw/applications.d/invoicer shows root root and -rw-r--r--. A typo in the file makes UFW print a warning naming the file.
Step 3 · Open ports to one subnet only
Invoicer's admin dashboard should never face the internet. Allow the whole profile, but only from your private network. Preview it first:
sudo ufw --dry-run allow from 10.20.0.0/24 to any app InvoicerLook for a line that combines -m multiport --dports 8080,8081 with -s 10.20.0.0/24. There is no IPv6 copy this time, because the source is an IPv4 subnet. When it looks right, add it for real:
sudo ufw allow from 10.20.0.0/24 to any app InvoicerThe same pattern works for a single port without a profile. Here a monitoring server on the private network scrapes a metrics exporter on port 9100:
sudo ufw --dry-run allow from 10.20.0.0/24 to any port 9100 proto tcp | grep -F -- '--dport 9100'sudo ufw allow from 10.20.0.0/24 to any port 9100 proto tcpWith a port number, proto tcp matters: leave it out and UFW opens both TCP and UDP. If you later edit the Invoicer profile's ports, run sudo ufw app update Invoicer so the rules that use it pick up the change.
Check it worked
sudo ufw statusYou see two new lines, something like Invoicer ALLOW 10.20.0.0/24 and 9100/tcp ALLOW 10.20.0.0/24. From a machine inside 10.20.0.0/24, curl -I http://<server-private-ip>:8080 reaches the app; from your laptop over the public address, the same request hangs until it times out.
Step 4 · See what the SSH limit rule counts
ufw limit is UFW's built-in brute-force brake. The man page says it denies an address that tries to open 6 or more connections within 30 seconds. A dry run shows how that is built:
sudo ufw --dry-run limit 22/tcp | grep -E 'recent|limit'The IPv4 part of the output contains three rules for port 22, something like:
-A ufw-user-input -p tcp --dport 22 -m conntrack --ctstate NEW -m recent --set
-A ufw-user-input -p tcp --dport 22 -m conntrack --ctstate NEW -m recent --update --seconds 30 --hitcount 6 -j ufw-user-limit
-A ufw-user-input -p tcp --dport 22 -j ufw-user-limit-acceptRead them in order:
- Every new connection to port 22 records the source address in the kernel's
recentlist. - If that address now has 6 or more entries from the last 30 seconds, the packet goes to
ufw-user-limit, which logs it with the prefix[UFW LIMIT BLOCK]and refuses it. - Anything else is accepted.
So from one address, the first five new connections in a 30-second window get through and the sixth is refused. Each refused attempt is recorded too, so a client that keeps hammering stays blocked until it goes quiet for 30 seconds. Connections that are already open are not affected; only new ones are counted.
That matters for tools that open many SSH connections in a burst: an Ansible run against this server, a script that calls scp in a loop, or a flaky mobile connection that drops and reconnects several times a minute. On a prepaid LTE or 4G link, where your address also changes between sessions, you cannot allowlist yourself reliably, so keep connections few instead. SSH connection sharing does that. Add this on your laptop, in ~/.ssh/config:
Host *
ControlMaster auto
ControlPath ~/.ssh/cm-%r@%h:%p
ControlPersist 10mLater sessions to the same host reuse the first connection and never reach the limit.
The dry run may also print Skipping unsupported IPv6 'limit' rule; a dry run assumes no IPv6 support for limit, while the real command checks your kernel and adds both. If your SSH rule is still allow (check with sudo ufw status), switch it to limit:
sudo ufw limit OpenSSHCheck it worked
sudo ufw status shows LIMIT IN (or LIMIT) next to OpenSSH for IPv4 and IPv6, with no separate ALLOW line for port 22. Limit is a coarse brake that counts connections, not failed logins. For bans based on failed passwords, add Fail2ban as in /tutorials/block-brute-force-logins-with-fail2ban.
Step 5 · Put rules in the right order
UFW checks your rules from the top, and the first rule that matches decides. A deny placed under an allow for the same port never fires. See the order with numbers:
sudo ufw status numberedEach rule has a number in square brackets, IPv4 rules first and their (v6) copies after. Say 203.0.113.0/24 is hammering your web server and you want it gone from every port, including the ones you allow to everyone. A plain ufw deny would land at the bottom, under 80,443/tcp ALLOW IN Anywhere, and do nothing. Insert it at the top instead.
Before you block a range, check that your own address is not in it: run echo $SSH_CLIENT in your SSH session and compare the first field. Denying your own address at position 1 cuts your session off as soon as the rule is added.Preview, then insert:
sudo ufw --dry-run insert 1 deny from 203.0.113.0/24
sudo ufw insert 1 deny from 203.0.113.0/24insert 1 puts the rule in position 1. sudo ufw prepend deny from 203.0.113.0/24 does the same without a number, and also handles IPv6 sources, which must sit above the other IPv6 rules rather than at position 1.
To remove a rule by number, list the rules again first, because the numbers shift after every insert and delete. Replace <number> with the number shown next to the rule you mean:
sudo ufw status numbered
sudo ufw delete <number>UFW prints the rule and asks you to confirm. Read it before you type y, and never delete the OpenSSH lines from an SSH session.
Check it worked
sudo ufw status numbered shows [ 1] Anywhere DENY IN 203.0.113.0/24 above your allow rules. sudo ufw show added lists the rules as you typed them, in the same order, which is the easiest view to paste into your own notes.
Step 6 · Choose a logging level and read the blocks
UFW has five logging levels:
off: no UFW logging.low(the default once you turn logging on): blocked packets that no rule matched, rate-limited, plus packets that hit a rule written withlog.medium: low, plus allowed packets that no rule matched, invalid packets and every new connection.high: medium without rate limiting, plus every packet, rate-limited.full: high with no rate limiting at all.
Keep low day to day. Raise it to medium while you chase a problem, then lower it again; high and full can write gigabytes a day on a busy server and fill a small VPS disk.
sudo ufw logging low
sudo ufw status verboseThe second command shows Logging: on (low). UFW logs through the kernel, so the lines are in the journal. If rsyslog is installed, they are also in /var/log/ufw.log. Show the five most recent blocks:
sudo journalctl -k -g 'UFW BLOCK' -n 5 --no-pagerOne line looks like this, wrapped here for reading:
Nov 26 09:14:02 web1 kernel: [UFW BLOCK] IN=eth0 OUT= MAC=...
SRC=198.51.100.23 DST=192.0.2.10 LEN=44 TOS=0x00 PREC=0x00 TTL=242
ID=54321 PROTO=TCP SPT=51544 DPT=3389 WINDOW=1024 RES=0x00 SYN URGP=0The fields that answer most questions:
IN=eth0: the interface the packet arrived on. An emptyIN=with a value inOUT=means an outgoing packet was blocked.SRCandDST: who sent it, and which of your addresses it was for.PROTO,SPTandDPT: protocol, the sender's port and the port they wanted on your server.DPTis the one to read.SYN: a new TCP connection attempt, which is what a port scan looks like.
The example is someone trying Windows remote desktop (3389) on a Linux server: background noise. A block on a port you meant to open, from an address you know, is a missing rule.
To see patterns, save a day of blocks to a file and count them:
mkdir -p ~/ufw-demosudo journalctl -k -g 'UFW BLOCK' --since today --no-pager > ~/ufw-demo/blocks.txtgrep -c 'UFW BLOCK' ~/ufw-demo/blocks.txt
grep -o 'SRC=[^ ]*' ~/ufw-demo/blocks.txt | sort | uniq -c | sort -rn | head -n 10
grep -o 'DPT=[0-9]*' ~/ufw-demo/blocks.txt | sort | uniq -c | sort -rn | head -n 10Check it worked
The first command prints the number of blocked packets today. The second lists the sending addresses with a count in front, busiest first, such as 3 SRC=198.51.100.23. The third does the same for the ports they tried. Scanners spread across many ports are normal. Repeated blocks on one of your own ports, such as DPT=8081 from a known address, point to a rule you still need, here an office or VPN address that is outside 10.20.0.0/24.
Step 7 · Add a rule the ufw command cannot write
The ufw command covers allow, deny, reject and limit by address, port, protocol and interface. For anything else, UFW reads raw iptables rules from /etc/ufw/before.rules (IPv4) and /etc/ufw/before6.rules (IPv6), and applies them before your own rules.
A common example is capping how many connections one address may hold open at once, so a single misbehaving client cannot use up your web server's workers. That needs the connlimit match, which the ufw command has no option for.
Keep a backup of the file before you edit it. A mistake inbefore.rulesmakesufw reloadfail, and the backup gets you back in one command.
sudo cp /etc/ufw/before.rules /etc/ufw/before.rules.baksudo nano /etc/ufw/before.rulesScroll to the bottom. The file ends with a comment warning you not to delete the COMMIT line, then COMMIT itself. Add these two lines directly above that final COMMIT:
# Cap open HTTPS connections at 40 per IPv4 address
-A ufw-before-input -p tcp --dport 443 --syn -m connlimit --connlimit-above 40 --connlimit-mask 32 -j REJECT --reject-with tcp-resetSave and close nano. The rule counts new connections (--syn) to port 443 from one address (--connlimit-mask 32) and resets any beyond 40 that are open at the same time. Forty is generous for browsers, which open about six per site; lower it only after watching real traffic. Many people can share one public address behind a mobile carrier's or a campus NAT, so a low cap can block a whole office or a whole network of phones at once.
sudo tail -n 4 /etc/ufw/before.rulesThe last lines are now the warning comment, your comment, your -A ufw-before-input ... connlimit ... rule and COMMIT.
Load it:
sudo ufw reloadFor IPv6, add the same rule to /etc/ufw/before6.rules with ufw6-before-input as the chain and --connlimit-mask 128.
Check it worked
sudo ufw reload prints Firewall reloaded. Then confirm the kernel has the rule:
sudo iptables -S ufw-before-input | grep connlimitYou see your rule, written back by iptables. If the reload printed ERROR: problem running ufw-init instead, the message names the line it could not parse. Put the backup back with sudo cp /etc/ufw/before.rules.bak /etc/ufw/before.rules, run sudo ufw reload again and fix the line before you retry.
Step 8 · Remove what you do not keep
If you followed along with the example names, take them out again. Replace the Invoicer rule with your own app's when you are ready:
sudo ufw delete allow from 10.20.0.0/24 to any app Invoicer
sudo ufw delete allow from 10.20.0.0/24 to any port 9100 proto tcp
sudo ufw delete deny from 203.0.113.0/24Then remove the profile, the saved log file, and the connection cap if you do not want it:
sudo rm /etc/ufw/applications.d/invoicer
rm -r ~/ufw-demo
sudo cp /etc/ufw/before.rules.bak /etc/ufw/before.rulessudo ufw reloadKeep /etc/ufw/before.rules.bak until you are sure, then delete it with sudo rm /etc/ufw/before.rules.bak.
Check it worked
sudo ufw status numbered shows only the rules you meant to keep, sudo ufw app list no longer lists Invoicer, and sudo grep connlimit /etc/ufw/before.rules prints nothing.
Next steps
You can now preview any change, keep multi-port apps tidy with profiles, scope ports to a network, order rules deliberately and tell from the logs what the firewall stopped.
- Ban addresses after failed logins rather than raw connection counts: /tutorials/block-brute-force-logins-with-fail2ban
- Write the same kind of policy directly in nftables, the layer UFW sits on: /tutorials/write-a-server-firewall-with-nftables
- Go back over the basics, including how Docker's published ports bypass UFW: /tutorials/set-up-ufw-firewall-ubuntu-26-04
Related tutorials
- Write Nginx location blocks that match what you expectYou will build a practice Nginx 1.30 server where every location block labels its responses, predict which block answers each of twelve URLs, check your answers with curl, and fix the alias, regex-order and proxy_pass mistakes that catch most people out.
- Write a server firewall with nftablesYou will write one /etc/nftables.conf with a default-drop input chain, rate-limited SSH, named address sets, counters and logging, and load it over SSH behind a timer that undoes it if you lose your connection.
- Watch a TCP connection open and close with tcpdumpYou will capture a curl request to a local web server with tcpdump on Ubuntu 26.04, read its handshake, data and teardown line by line, see the reset a closed port sends, and save, filter and rotate captures as pcap files.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials