Introduction
UFW sits on top of nftables on modern Ubuntu and Debian systems. Configuring a firewall correctly means setting a default-deny policy, allowing only the ports your services need, and verifying the ruleset before you lock yourself out of SSH.
Prerequisites
Before changing firewall rules, confirm you have console access to the server through your provider’s web console, IPMI, or a separate management network. A mistyped rule can drop your SSH session with no recovery path.
Check which firewall backend is active:
sudo ufw status verbosesudo nft list rulesetOn Ubuntu 22.04 and later, UFW writes to nftables by default. On older releases it may use iptables. Check the backend with:
sudo update-alternatives --display iptablesIf the output points to iptables-nft or nftables, UFW is already using the nftables backend.
Default Policies
Start with the strictest defaults and open only what you need:
sudo ufw default deny incomingsudo ufw default allow outgoingsudo ufw default deny routedThe deny routed policy blocks forwarded traffic between interfaces. If you run a VPN gateway or router, change this to allow routed and add explicit forwarding rules instead.
Do not enable UFW yet. Add your SSH rule first.
Allowing SSH Before Enabling UFW
Locking yourself out is the most common firewall mistake. Add the SSH rule and verify it appears in the list before enabling the firewall:
sudo ufw allow 22/tcp comment 'SSH management'sudo ufw status numberedIf you run SSH on a non-standard port, use that port instead. If you connect from a known IP range, restrict the source:
sudo ufw allow from 203.0.113.0/24 to any port 22 proto tcp comment 'SSH from office'The comment field makes rules easier to audit later. UFW stores comments in the nftables ruleset as metadata.
Adding Service Rules
Add rules for each service the server runs. Common examples:
Web server:
sudo ufw allow 80/tcp comment 'HTTP'sudo ufw allow 443/tcp comment 'HTTPS'Database access restricted to an application subnet:
sudo ufw allow from 10.0.0.0/24 to any port 5432 proto tcp comment 'PostgreSQL from app servers'DNS resolver:
sudo ufw allow 53/udp comment 'DNS'sudo ufw allow 53/tcp comment 'DNS'Rate-limit SSH to slow brute-force attempts:
sudo ufw limit 22/tcp comment 'SSH rate limit'The limit keyword allows 6 connections within 30 seconds. Connections beyond that are dropped. This does not replace fail2ban or crowdsec for persistent attackers, but it reduces noise.
Enabling UFW
Once all rules are in place, enable the firewall:
sudo ufw enablesudo ufw status verboseThe verbose output shows default policies, logging level, and each rule with its comment. If anything looks wrong, disable immediately and fix:
sudo ufw disableWorking Directly with nftables
UFW generates an nftables ruleset under the inet filter table. You can inspect it directly:
sudo nft list table inet filterThe UFW-managed chain looks like this:
table inet filter { chain ufw-user-input { tcp dport 22 accept comment "SSH management" tcp dport 80 accept comment "HTTP" tcp dport 443 accept comment "HTTPS" } chain ufw-before-input { iif "lo" accept ct state established,related accept ct state invalid drop ... }}UFW manages the ufw-user-input chain. You should not edit this chain manually because UFW will overwrite it on reload. If you need custom rules that UFW cannot express, create a separate table:
sudo nft add table inet customsudo nft add chain inet custom input { type filter hook input priority 10 \; policy accept \; }sudo nft add rule inet custom input tcp dport 8443 accept comment "Custom service"Using a separate table avoids conflicts with UFW’s generated ruleset. The priority value controls evaluation order. UFW’s chains run at priority 0, so a custom chain at priority 10 runs after them.
Persisting Custom nftables Rules
Rules added with nft add are lost on reboot. To persist them, save the ruleset and load it at boot:
sudo nft list ruleset > /etc/nftables.confOn Debian and Ubuntu, enable the nftables service:
sudo systemctl enable nftablessudo systemctl start nftablesThe service reads /etc/nftables.conf at startup. If you use both UFW and a custom nftables file, conflicts can arise. UFW also writes its own rules at boot through its service. Test the full boot sequence in a staging environment before deploying to production.
A safer approach is to keep all rules in UFW and use UFW’s application profiles for services that need complex matching. If UFW cannot express a rule, document the custom nftables rules and test them across reboots.
Application Profiles
UFW ships with predefined profiles in /etc/ufw/applications.d/. List them:
sudo ufw app listShow a profile’s details:
sudo ufw app info 'Nginx Full'Enable a profile:
sudo ufw allow 'Nginx Full'Application profiles expand to multiple ports and protocols. Creating your own profile is useful for custom services. Create a file at /etc/ufw/applications.d/myapp:
[MyApp]title=My Applicationdescription=Custom application on ports 8080 and 8443ports=8080,8443/tcpThen reload UFW’s profile cache and apply:
sudo ufw app update MyAppsudo ufw allow MyAppLogging
Enable logging to see dropped packets:
sudo ufw logging onsudo ufw logging mediumLog levels: low, medium, high, full. Medium logs dropped packets and new connections. High logs all packets. Full logs every packet including those that match allow rules, which generates heavy I/O on busy servers.
Logs go to /var/log/ufw.log and the kernel journal. View recent entries:
sudo journalctl -k | grep UFWA typical dropped-packet log entry:
[UFW BLOCK] IN=eth0 OUT= MAC=... SRC=198.51.100.7 DST=203.0.113.5 LEN=60 TOS=0x00 PREC=0x00 TTL=54 ID=12345 DF PROTO=TCP SPT=54321 DPT=3306 WINDOW=29200 RES=0x00 SYN URGP=0This tells you the source IP, destination port, and protocol. Use it to identify scanning traffic or misconfigured clients.
Troubleshooting
Connection Refused vs. Connection Timed Out
If the firewall drops a packet, the client sees a connection timeout. If the service is not listening, the client sees connection refused. This distinction helps isolate firewall issues from application issues.
Test from a remote host:
nc -vz 203.0.113.5 443A timeout suggests a firewall drop. A refused error means the firewall allowed the packet but nothing is listening on that port.
Verifying Rules Match Traffic
Check that a rule exists for the port and protocol:
sudo ufw status numbered | grep 443If the rule exists but traffic is still blocked, check the default policy and rule ordering. UFW evaluates rules top to bottom. A deny rule placed before an allow rule for the same port will block the traffic.
Restoring Access After Lockout
If you lock yourself out of SSH, use your provider’s console to disable UFW:
sudo ufw disableOr flush nftables entirely:
sudo nft flush rulesetFlushing removes all rules including UFW’s. Rebuild from scratch after restoring access.
UFW Not Starting on Boot
Check the service status:
sudo systemctl status ufwIf it shows inactive, enable it:
sudo systemctl enable ufwsudo systemctl start ufwOn some systems, UFW depends on the netfilter-persistent service. Check for conflicts:
sudo systemctl status netfilter-persistentIf both services try to load rules, they can overwrite each other. Disable one or consolidate rules into a single service.
IPv6 Rules
UFW manages IPv4 and IPv6 rules separately. If your server has IPv6 enabled, rules apply to both by default. Check /etc/default/ufw:
IPV6=yesIf IPv6 is disabled on the server but IPV6=yes is set, UFW will fail to apply rules. Set it to no if you do not use IPv6.
Hardening Beyond Basic Rules
Disable Ping Response
By default, UFW allows ICMP echo requests. To drop ping traffic, edit /etc/ufw/before.rules and add before the final COMMIT line:
-A ufw-before-input -p icmp --icmp-type echo-request -j DROPThen reload:
sudo ufw reloadThis only affects IPv4. For IPv6, edit /etc/ufw/before6.rules with the same rule.
Restrict Outbound Traffic
The default allow outgoing policy lets any process make outbound connections. For stricter control, set outgoing to deny and allow only specific destinations:
sudo ufw default deny outgoingsudo ufw allow out to 93.184.216.34 port 443 proto tcp comment 'API endpoint'sudo ufw allow out 53/udp comment 'DNS'sudo ufw allow out 123/udp comment 'NTP'This breaks most applications unless you whitelist every outbound destination. It is practical for high-security environments like bastion hosts or payment processing servers, but adds maintenance overhead.
Rate Limiting with nftables Directly
For more granular rate limiting than UFW’s limit keyword, use nftables meters. This requires a custom table:
sudo nft add table inet ratelimitsudo nft add chain inet ratelimit input { type filter hook input priority 5 \; policy accept \; }sudo nft add rule inet ratelimit input tcp dport 22 ct state new meter ssh-meter { ip saddr limit rate 10/minute burst 5 packets } acceptsudo nft add rule inet ratelimit input tcp dport 22 ct state new dropThis allows 10 new SSH connections per minute per source IP with a burst of 5. The meter tracks each source IP independently.
Trade-offs
UFW trades flexibility for simplicity. It cannot express complex matching like source port ranges, time-based rules, or multi-port sets without dropping to nftables directly. For a standard web server or application host, UFW covers 95% of use cases with far less risk of misconfiguration.
nftables directly offers full control but requires understanding chain priorities, hook types, and table families. A mistake in a raw nftables ruleset can be harder to debug than a UFW rule because there is no abstraction layer to catch syntax errors before they reach the kernel.
Running both UFW and custom nftables tables works, but you must track which tool owns which rule. When UFW reloads, it flushes and rebuilds its own chains. Custom tables survive because they are separate, but their priority and interaction with UFW’s chains must be tested after every UFW upgrade.
Conclusion
Start with default-deny policies, allow SSH before enabling the firewall, add service rules with comments, and verify with ufw status verbose and direct connection tests. For rules UFW cannot express, use a separate nftables table with a distinct priority. Keep logging at medium level, restrict outbound traffic only where the maintenance cost is justified, and always have console access before changing firewall rules on a remote server.