Linux Firewall Configuration: UFW and iptables Practice
The firewall is the first line of defense for any server exposed to the internet. By default Linux does not restrict inbound traffic, so a freshly installed system that opens business ports directly exposes management services such as MySQL and Redis to the public network. The right approach is "deny inbound by default, allow on demand", plus rate limiting and source restrictions for management entry points like SSH.
If you have not yet done basic security setup, start with the Server Initialization Security Script article, then refine the rules with this guide.
UFW: the easiest default configuration
UFW is a front-end for iptables/nftables with intuitive syntax, well suited to most single-server scenarios.
ufw default deny incoming
ufw default allow outgoing
ufw allow 22/tcp
ufw allow 80/tcp
ufw allow 443/tcp
ufw limit ssh
ufw enable
ufw allow 51312opens TCP+UDP,ufw allow 51312/udpopens UDP only, and port ranges use51312:51314.ufw limit sshautomatically rate-limits any IP that attempts 6 or more connections within 30 seconds, ideal for management entry points.- Use
ufw status verboseto review rules; user rules are stored in/etc/ufw/user.rules.
Note: Docker bypasses UFW by writing its own iptables rules, so you need a solution like ufw-docker to keep container traffic under control.
iptables: rule chains and persistence
Use iptables directly when you need fine-grained control. A basic inbound rule set:
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT
iptables -A INPUT -j DROP
iptables rules are not persistent by default and are lost on reboot. Save them with iptables-save > /etc/iptables/rules.v4 and install iptables-persistent.
Restricting to specific source IPs is also common — for example, allowing only your office's egress range to reach a management port:
iptables -A INPUT -p tcp --dport 22 -s 203.0.113.0/24 -j ACCEPT
iptables -A INPUT -p tcp --dport 22 -j DROP
For entry points like SSH that get brute-forced constantly, hashlimit gives connection-level rate limiting that is more controllable than ufw limit:
iptables -A INPUT -p tcp --dport 22 -m state --state NEW \
-m hashlimit --hashlimit-above 3/min --hashlimit-burst 5 \
--hashlimit-name ssh -j DROP
nftables: the next-generation framework
nftables replaces iptables as the kernel's default framework with more unified syntax. A single inet table can handle IPv4 and IPv6 together:
table inet filter {
chain input {
type filter hook input priority filter; policy drop;
ct state established,related accept
tcp dport { 22, 80, 443 } accept
}
}
Save rules with nft list ruleset > /etc/nftables.conf; nftables.service reloads them automatically after reboot. For port forwarding (say, forwarding public 8443 to an internal host's 443), use a nat table:
table ip nat {
chain prerouting {
type nat hook prerouting priority dstnat; policy accept;
tcp dport 8443 dnat to 192.168.1.10:443
}
}
Common scenario checklist
- Web servers: open 80/443, and 22 when needed; close everything else.
- Databases: allow only internal network ranges to reach 3306/5432; never expose them publicly.
- Management entry points: restrict SSH source IPs and rate-limit connections, combined with SSH Hardening.
- Periodic audits: export and review rules regularly with
nft list rulesetoriptables -S.
Rule design principles
A firewall rule's priority and match order decide how secure the result is. Three principles cover the design:
- Default deny: inbound is an allow-list; anything not explicitly written is rejected.
- Minimum exposure: open only the ports the business and operations need; databases, Redis and admin panels stay off the public internet.
- Minimal source scope: restrict by IP or CIDR wherever possible instead of opening to the world, and always scope management entry points to known sources.
Validate rule changes on a small scale before rolling them out, so a busy traffic window does not lose the service. Keep rule files under version control and record changes alongside server operations tips.
A worked example: hardening a WordPress box
For a typical WordPress server, a full hardening pass usually has four steps: first, inventory what must be exposed — 80/443 for the web tier and certificate renewal, 22 only for operations, and database and Redis bound strictly to the internal network; second, allow 22/80/443 with UFW and deny everything else by default; third, restrict SSH to your office egress range and enable ufw limit ssh; finally, add another source restriction to high-value entry points such as a control panel or phpMyAdmin. When done, export the rule list with ufw status numbered and archive it for later comparison.
This allow-list covers the common ports; anything not listed stays closed by default:
| Service | Port | Recommendation |
|---|---|---|
| SSH | 22 | Restrict source + rate limit |
| HTTP/HTTPS | 80/443 | Open to the world |
| MySQL/PostgreSQL | 3306/5432 | Internal network only |
| Redis | 6379 | Internal only, no 0.0.0.0 binding |
| Control panel | Custom | Source-restrict or VPN |
- Can UFW and iptables coexist:UFW is just a front-end for iptables/nftables — do not hand-maintain both at once, or rules will overwrite each other. Pick one backend: nftables or iptables.
- Why does Docker break the firewall after publishing ports:Docker writes directly to iptables' FORWARD chain, bypassing UFW's INPUT policy. Enable
ufw-dockeror use NetworkPolicy at the orchestration layer to contain container traffic. - Do cloud security groups replace a server firewall:No. Security groups filter at the virtual network layer; the local firewall is the last line of defense in depth. Configure both.
- What if I forget about IPv6:Many hosts allow IPv6 by default while only configuring IPv4 rules — a backdoor. UFW manages both together; with iptables, configure
ip6tablesseparately; with nftables, aninettable covers both stacks at once.
Verify and enable
Do not rely on intuition after writing rules — verify with commands: ufw status verbose shows the active policy, ufw show added lists pending rules, and nft list ruleset (nftables backend) or iptables -S (iptables backend) shows the actual chains. After rollout, keep firewall logs enabled (ufw logging on) for a while so you can spot legitimate traffic being dropped, then decide whether to tighten further.
A common gotcha: running ufw enable in a remote session applies rules immediately, and if you forgot to allow SSH, the session dies on the spot. The safe sequence is to allow SSH first, then run ufw enable --force, keeping the current session open to verify. If you do get locked out, recover through your cloud provider's VNC or serial console.
16IDC Observation
For most sites, UFW's default-deny policy plus a few allow rules is enough; move up to iptables/nftables only when you need port forwarding, multiple NICs, or container networking. Beyond the firewall, layer application-level protections such as Security Headers and Web Application Firewalls on top of network rules to build defense in depth. Browse the full list back in the Security Hardening category.
Source: https://wiki.archlinux.org/title/Uncomplicated_Firewall
Reference: nftables wiki https://wiki.nftables.org/; UFW man page https://manpages.debian.org/ufw
Configuration & Integration Examples
Example 1: nftables — deny by default, then allow explicitly
nft add table inet filter
nft add chain inet filter input '{ type filter hook input priority 0; policy drop; }'
nft add rule inet filter input ct state established,related accept
nft add rule inet filter input iif lo accept
nft add rule inet filter input tcp dport { 22, 80, 443 } accept
nft add rule inet filter input ip protocol icmp icmp type echo-request accept
# persist to a file so it survives reboots
nft list ruleset > /etc/nftables.conf
systemctl enable --now nftables
policy drop plus ct state established,related accept is the minimum viable pair: new connections arrive only through explicit rules, while established flows are not cut off by your own policy.
Example 2: Day-to-day allows with ufw and firewalld
# Ubuntu/Debian: allow SSH before enabling, or you lock yourself out
ufw allow 2222/tcp
ufw allow 'Nginx Full'
ufw --force enable
ufw status verbose
# RHEL family
firewall-cmd --permanent --add-service=http --add-service=https
firewall-cmd --permanent --add-port=2222/tcp
firewall-cmd --reload
firewall-cmd --list-all
--permanent and --reload go together: permanent rules without a reload do nothing, while runtime-only rules vanish on reboot.
Order of Enabling Rules in a Remote Session, and Rolling Back a Disconnect
ufw enable applies rules the moment it runs, so an unfilled SSH allow rule drops the live session. The safer order is ufw allow 22/tcp first, then ufw enable --force, keeping the session open to run ufw status verbose, with the provider's VNC or serial console as the recovery path.
iptables and nftables default-deny behave the same way: allow ESTABLISHED,RELATED traffic and port 22 before switching the chain policy to DROP, or the established SSH connection is cut by the new policy. Persist rules according to the backend — iptables-save into /etc/iptables/rules.v4, or nft list ruleset overwriting /etc/nftables.conf.
| Action | Where the disconnect comes from | Prevention | Rollback |
|---|---|---|---|
Running ufw enable remotely |
Port 22 not allowed when the rules take effect | ufw allow 22/tcp first, then ufw enable --force |
Log in via VNC/serial console and fix the rules |
| Switching an iptables chain policy to DROP | Established connections not allowed | Add ESTABLISHED,RELATED and port 22 rules first |
Run iptables -F from the console |
nftables policy drop |
Rule order blocks management traffic | Allow ct state established,related and port 22 first |
nft flush ruleset from the console, then reload config |
| Docker published ports | Docker writes the FORWARD chain directly, bypassing UFW | Enable ufw-docker or move policy to the orchestrator |
Stop the container and remove the matching iptables rules |
Limitations
- Figures reflect public information at publication; terms, prices and quotas follow the provider's current published terms.
- This article reflects public information as of 2026-08-06; terms, prices and quotas follow the provider's current published terms.
- Third-party capability and limit statements follow their official documentation; no further commitment is implied here.
FAQ
What prerequisite makes UFW apply to containers?
That container traffic does not bypass UFW. Docker can publish 3306 or 6379 by writing iptables rules on the FORWARD chain, skipping the INPUT policy, so deny and limit rules never touch containers; enable ufw-docker, or enforce NetworkPolicy at the orchestration layer, to bring that traffic back under control.
Why do allowed ports still get blocked?
Check the layer first, then the order of 3 things. ufw status verbose shows the active policy, ufw show added lists pending rules, and iptables -S or nft list ruleset shows the real chains; with firewalld, permanent rules without --reload do nothing, and iptables rules vanish on reboot unless iptables-persistent is installed.
Should the cloud security group replace UFW?
No — they cover different layers. The security group filters at the virtual network edge and should stop cross-instance traffic before it arrives; the host firewall is the last hop, handling per-port minimum exposure and SSH rate limits such as 6 connections in 30 seconds. Run both.
When shouldn't UFW carry the rules?
When you need port forwarding, multiple NICs or container networking. UFW wraps iptables and nftables, but dnat rules such as public 8443 to internal 443, or hashlimit connection limits, need native syntax; for a single host opening only 22, 80 and 443, three UFW lines are enough.
Related Providers
- Cloudflare WAF: use it when rules must sit ahead of the origin so attack traffic never reaches iptables.
- Sucuri: after a compromise, clean the site and add application-layer protection there, which host firewalls cannot cover.
- ESET: use it when the server also needs host-level protection, and check Linux distribution support first.
Community & Resources
Official docs and communities
- iptables(8) — table/chain structure and match targets
- nftables man page — the complete nft command syntax
- nftables wiki — side-by-side examples for migrating from iptables
- firewalld documentation — zones, services and permanent vs runtime
Learning resources and tools
- UFW man page —
allow,limitand status queries - Stack Overflow: iptables — rule ordering and connection tracking
- Stack Overflow: nftables — syntax and set usage
- Stack Overflow: firewalld — why a rule appears to do nothing
Original source: ArchWiki UFW Documentation ↗