Advanced ufw firewall rules (limit, allow from IP, delete, insert)
Advanced ufw rules restrict ports to specific source addresses, rate limit SSH, and rely on rule order, so you control exactly who reaches each service.
- Updated Nov 27, 2026
- Markdown
Write ordered ufw rules that limit SSH, restrict ports to chosen IPs, delete rules by number and turn on logging safely.
- Ubuntu or Debian server with ufw installed
- A second SSH session open
The basic ufw allow and ufw deny commands cover a simple server. Real servers need a bit more: SSH open only to known addresses, brute-force limits, rules in the right order, and a way to remove rules cleanly. This lesson covers those, building on set up a firewall with ufw.
Firewall mistakes lock people out of their own servers. Before changing rules, open a second SSH session and keep it open, and know where your provider’s web console is.
How it works#
ufw is a front end for the kernel’s packet filter. You describe rules, and ufw writes them into its chains. For incoming traffic it works down the rule list and applies the first rule that matches. Rules that match nothing fall through to the default policy, usually deny incoming and allow outgoing.
Because of this, order is part of the meaning. allow 22 followed by deny from 198.51.100.7 never blocks that address, since the first rule matches it. Rules you add go to the end of the list unless you use ufw insert. ufw also keeps separate IPv4 and IPv6 versions of most rules, which is why you see (v6) lines.
Step 1: Check the state before changing anything#
sudo ufw status verbose
sudo ufw status numberedverbose shows the default policies and logging level. numbered shows rule numbers. If ufw says Status: inactive, nothing is enforced yet. Add your rules first and only then enable it.
Step 2: Allow from one address to one port#
Restrict a service to a known source:
sudo ufw allow from 192.0.2.25 to any port 22 proto tcp
sudo ufw allow from 192.0.2.0/24 to any port 5432 proto tcpThe first limits SSH to a single address, the second opens a database port to a private range. This is much safer than opening the port to everyone. The risk is your own address changing, so keep a fallback such as the provider console, and consider the hardened SSH settings as your main defense instead of an address list.
Step 3: Rate limit with ufw limit#
sudo ufw limit 22/tcplimit allows the port but denies an address that opens too many new connections in a short window. The exact threshold is built into ufw, so check the man page if you need it. It is a simple companion to fail2ban, but fail2ban gives you finer control over ban lengths. You can use both.
Step 4: Use application profiles#
Packages can register named profiles:
sudo ufw app list
sudo ufw app info 'Nginx Full'
sudo ufw allow 'Nginx Full'A profile bundles the ports a package needs, for example 80 and 443 for a web server. The names depend on installed packages, so read app list rather than guessing. Quote names that contain spaces.
Step 5: Control order with insert and delete#
Put a deny in front of a broader allow:
sudo ufw insert 1 deny from 198.51.100.7Remove rules by number:
sudo ufw status numbered
sudo ufw delete 3Numbers shift after each delete, so list again before the next. You can also delete by repeating the rule with delete in front: sudo ufw delete allow 80/tcp. That is safer in scripts because it does not depend on position.
Step 6: Turn on logging#
sudo ufw logging lowLevels are off, low, medium, high and full. Blocked packets are written to the kernel log, usually /var/log/ufw.log on Ubuntu, with lines marked [UFW BLOCK]. Start with low. Higher levels can fill a disk on a busy server, so check the size now and then. See read logs with journalctl for reading them.
Step 7: Enable carefully, and mind Docker#
If ufw is not yet enabled, add the SSH allow rule first, keep your second session open, then:
sudo ufw enableufw warns that it may disrupt existing SSH connections. With the allow rule in place, it will not. Then open a new terminal and log in to prove access before you close anything.
Docker needs a separate warning. A published container port is wired in by Docker’s own rules, which are checked before ufw’s. A ufw deny 8080 often does not stop traffic to a container published on 0.0.0.0:8080. The reliable fix is to publish internal services on 127.0.0.1 only. See publish container ports safely.
Check it worked#
sudo ufw status verbose
sudo ss -tulpnFrom another machine, test the ports you meant to open and the ones you meant to close, for example with nc -vz 203.0.113.10 22. A rule that exists but has never been tested is a guess.
Edge cases and gotchas#
- First match wins. A broad allow above a specific deny makes the deny useless. Use
insert. - v6 rules. If IPv6 is enabled, rules are added for both families. If
IPV6=noin/etc/default/ufw, v6 traffic is not filtered by these rules. - Existing connections. Enabling ufw does not drop established SSH sessions, but a restart of networking can. Do not rely on this.
- Deleting by number in a loop. Numbers change after each delete, so deleting 3, 4, 5 in turn removes the wrong rules. Delete from the highest number down.
- Docker bypass. Published ports skip ufw’s input rules. Test from outside, not by reading
ufw status. - Outgoing rules. The default allows all outgoing traffic. Restricting it breaks updates and DNS unless you add rules for them.
Troubleshooting#
| Symptom | Likely cause | Fix |
|---|---|---|
ERROR: Could not find a profile matching 'nginx' | Profile name is different | Run sudo ufw app list and use the exact name |
| Locked out after enable | No SSH allow rule | Use the provider console, sudo ufw allow 22/tcp |
ERROR: Invalid position '5' | Fewer rules than the position | Check ufw status numbered, use a lower number |
| Deny rule does not block | An allow rule sits above it | ufw insert 1 deny from ... |
| Container port still reachable | Docker’s rules skip ufw | Bind to 127.0.0.1 or filter in DOCKER-USER |
Skipping adding existing rule | Same rule already present | Check ufw status numbered |
| No entries in ufw.log | Logging is off | sudo ufw logging low |
Quick reference#
sudo ufw status numbered
sudo ufw allow from 192.0.2.25 to any port 22 proto tcp
sudo ufw limit 22/tcp
sudo ufw insert 1 deny from 198.51.100.7
sudo ufw delete 3
sudo ufw app list
sudo ufw logging lowRelated lessons#
- Set up a firewall with ufw: default policies and first rules.
- Publish container ports safely: why Docker ports bypass ufw and how to bind to localhost.
- Harden SSH server configuration: the SSH settings behind the firewall rule.
- Find what is using a port: confirm what listens before you open it.
- Audit a Linux server: list listening sockets and review exposure.
Next#
Continue with Unattended security updates and reboots.
Try it: Write ordered ufw rules
Practise on a test server with a second SSH session open. Never enable the firewall without an SSH allow rule.
Want a real machine? Free browser labs: Killercoda
Check what you learned
Frequently asked questions
What does ufw limit do?
ufw limit allows a port but denies an address that makes too many new connections in a short time. It is meant for services like SSH that attract brute-force attempts.
How do I delete a ufw rule?
Run sudo ufw status numbered, then sudo ufw delete 3 to remove rule number 3. Numbers shift after each delete, so list again before the next one.
Does rule order matter in ufw?
Yes. ufw checks rules from the top and uses the first one that matches. Put specific rules before general ones, or use ufw insert to place a rule at a chosen position.
Why does ufw not block my Docker container ports?
Docker adds its own firewall rules for published ports, and they are evaluated before ufw's rules. Bind published ports to 127.0.0.1 or use the DOCKER-USER chain.
Sources
Keep going: guides and tutorials
- Manage Secrets Self-Hosted: Env Vars and Master Key Rotation Set env vars and encrypted secrets on a self-hosted server, apply changes safely, and rotate the master key with no downtime without locking yourself out.
- Install a Self-Hosted PaaS on Your Own Server in Five Minutes One installer download, one setup token, one sample app. The full Levelrail install on a fresh Linux server, with the checks and the fixes.