Overview and What You Will Learn
A Linux firewall filters network packets using rules in the kernel's netfilter framework. iptables writes those rules directly, and ufw is a simpler front end that writes iptables rules for you. A default-deny firewall blocks everything and opens only the ports a server must expose.
By the end of this lab you will:
- Explain how netfilter, iptables, and ufw relate
- Trace a packet through the PREROUTING, INPUT, FORWARD, and OUTPUT hooks
- Build a complete default-deny iptables ruleset in a safe order
- Manage individual rules by number, insert, and delete
- Persist rules across reboots
- Configure ufw for the same policy
- Close the Docker and ufw bypass with the DOCKER-USER chain
Why This Matters in Production
A fresh server accepts connections on every listening port from anywhere. A database port opened by mistake after a rebuild is typically found by internet scanners within minutes and then hit with brute-force login attempts. Default-deny makes unlisted ports silent, so a forgotten service stays unreachable instead of exposed.
Platform teams at companies such as Shopify and Grab pair host firewalls with network-level controls, so a single missed rule does not expose a service on its own.
Core Principles
Packets pass through fixed points in the kernel. Rules in a chain are checked top to bottom and the first match decides the packet's fate, so order matters.
nat: DNAT] B --> C{Destination is this host?} C -->|Yes| D[INPUT chain
filter table] C -->|No| E[FORWARD chain
filter table] D --> F[Local process
nginx, sshd] F --> G[OUTPUT chain
filter table] G --> H[POSTROUTING
nat: SNAT] classDef hook fill:#326CE5,color:#ffffff classDef decide fill:#DBEAFE,color:#1E293B classDef proc fill:#10B981,color:#ffffff class B,D,E,G,H hook class C decide class F proc
Here is how one rule breaks down:
iptables -A INPUT -p tcp --dport 22 -s 10.0.0.0/8 -j ACCEPT | | | | | | | chain protocol dest port source target append| Term | Meaning |
|---|---|
| ACCEPT | Let the packet through |
| DROP | Discard silently, the sender times out |
| REJECT | Discard and send an error back |
| LOG | Record the packet and keep evaluating rules |
Rememberiptables rules live in memory and vanish on reboot unless you save them. Modern distributions may run iptables on top of nftables (
iptables-nft), and the commands in this lab work the same way.
Detailed Step-by-Step Practical Lab
Milestone 1: How to List Current iptables Rules
sudo iptables -L -n -v # One chain, with line numbers for later deletessudo iptables -L INPUT -n -v --line-numbers # Default policiessudo iptables -S | grep -- '-P'# -P INPUT ACCEPT <- everything allowed, the risky default# -P FORWARD ACCEPT# -P OUTPUT ACCEPT # NAT table (port forwarding and Docker)sudo iptables -t nat -L -n -vMilestone 2: How to Build a Default-Deny iptables Ruleset Safely
Add the allow rules first and change the default policy last. Before you start, schedule an automatic rollback so a mistake cannot lock you out for good.
# Safety net: flush rules and reopen the policy in 5 minutesecho 'iptables -P INPUT ACCEPT; iptables -F INPUT' | sudo at now + 5 minutes# 1. Allow replies to connections this server startedsudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT # 2. Allow loopback so local services can talk to each othersudo iptables -A INPUT -i lo -j ACCEPT # 3. Allow SSH from the internal network onlysudo iptables -A INPUT -p tcp --dport 22 -s 10.0.0.0/8 -j ACCEPT # 4. Allow HTTP and HTTPS from anywheresudo iptables -A INPUT -p tcp --dport 80 -j ACCEPTsudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT # 5. Allow the application port from the internal network onlysudo iptables -A INPUT -p tcp --dport 4000 -s 10.0.0.0/8 -j ACCEPT # 6. Allow ping for monitoringsudo iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT # 7. Log what is about to be dropped, rate limitedsudo iptables -A INPUT -m limit --limit 5/min -j LOG --log-prefix "iptables-dropped: " # 8. Set default policies LASTsudo iptables -P INPUT DROPsudo iptables -P FORWARD DROPsudo iptables -P OUTPUT ACCEPT # Verify, then open a second SSH session to confirm you can still log insudo iptables -L INPUT -n -v --line-numbersOnce the second session works, cancel the rollback with atq to list the job and sudo atrm JOB_ID to remove it.
Common MistakeSetting
iptables -P INPUT DROPbefore the allow rules blocks all incoming traffic, including your own SSH session. Build the allow rules first, test from a second terminal, and set the DROP policy as the final step.
SecurityKeep your current SSH session open while you change firewall rules. It is your only way back if a rule blocks new connections.
Milestone 3: How to Insert, Delete, and Test Individual Rules
# Insert at the top so a specific IP is matched firstsudo iptables -I INPUT 1 -p tcp --dport 22 -s 203.0.113.10 -j ACCEPT # Delete by line number or by exact specificationsudo iptables -D INPUT 3sudo iptables -D INPUT -p tcp --dport 80 -j ACCEPT # Replace the rule at position 2sudo iptables -R INPUT 2 -p tcp --dport 22 -s 10.0.0.0/8 -j ACCEPT # Check whether a rule exists (exit code 0 = yes, 1 = no)sudo iptables -C INPUT -p tcp --dport 22 -s 10.0.0.0/8 -j ACCEPTecho $?Flushing a chain with sudo iptables -F INPUT while the policy is DROP blocks all traffic, so reset the policy to ACCEPT first.
Milestone 4: How to Persist iptables Rules Across Reboots
# Debian and Ubuntu: iptables-persistentsudo apt install iptables-persistentsudo iptables-save | sudo tee /etc/iptables/rules.v4sudo ip6tables-save | sudo tee /etc/iptables/rules.v6 # Restore manually if neededsudo iptables-restore < /etc/iptables/rules.v4 # RHEL, CentOS, Amazon Linux: iptables-servicessudo yum install iptables-servicessudo systemctl enable --now iptablessudo service iptables save# Saved to /etc/sysconfig/iptablesAfter a reboot, run sudo iptables -L -n -v to confirm the rules loaded. Remember the IPv6 rules too: an open IPv6 path bypasses an IPv4-only firewall.
Milestone 5: How to Configure ufw for the Same Policy
ufw is the standard on Ubuntu servers. Allow SSH before you enable it.
sudo ufw status verbose # Defaultssudo ufw default deny incomingsudo ufw default allow outgoingsudo ufw default deny routed # Allow SSH from the internal network, then web trafficsudo ufw allow from 10.0.0.0/8 to any port 22 proto tcpsudo ufw allow 80/tcpsudo ufw allow 443/tcp # Application port from the internal network onlysudo ufw allow from 10.0.0.0/8 to any port 4000 proto tcp # Rate limit SSH to slow brute-force attempts (alternative to the SSH rule above)sudo ufw limit 22/tcp # Turn it onsudo ufw enable # Review and remove by numbersudo ufw status numberedsudo ufw delete 3ufw persists its rules automatically. sudo ufw reset wipes them all.
Milestone 6: How to Fix the Docker and ufw Bypass
Docker publishes ports by adding its own rules to the nat table and the FORWARD path, so a container started with -p 80:80 can be reachable from the internet even when ufw denies port 80. Rules in the DOCKER-USER chain run before Docker's own rules, which makes it the supported place to filter.
# See Docker's rulessudo iptables -L DOCKER -n -vsudo iptables -L DOCKER-USER -n -v # Allow replies first, otherwise the block below also cuts container return trafficsudo iptables -I DOCKER-USER -m conntrack --ctstate ESTABLISHED,RELATED -j RETURN # Then drop anything arriving on eth0 from outside the internal networksudo iptables -I DOCKER-USER 2 -i eth0 ! -s 10.0.0.0/8 -j DROPThe preferred fix is to publish only on localhost and put a reverse proxy in front:
# Reachable from the worlddocker run -d -p 80:80 nginx # Reachable only from this hostdocker run -d -p 127.0.0.1:8080:80 nginxTipDOCKER-USER sees packets after destination NAT, so the destination port is the container port. To match the published host port, use
-m conntrack --ctorigdstport 80.
RememberSetting
"iptables": falsein/etc/docker/daemon.jsonstops Docker from touching iptables, but then you must write all container networking rules yourself. Most teams avoid it.
Production Best Practices & Common Pitfalls
A good firewall policy is small, explicit, and tested from outside.
- Use default-deny for incoming traffic and allow only what each server must serve.
- Restrict SSH to a VPN or office CIDR, and add
ufw limitor fail2ban for anything public. - Log before the default drop, with a rate limit so logs do not fill the disk.
- Save rules after every change, and keep IPv4 and IPv6 policies aligned.
- Test from another network with
nmap -Pn 10.0.1.50or a similar scan to see what is truly exposed.
| Mistake | Problem | Fix |
|---|---|---|
| DROP policy before allow rules | Locked out immediately | Allow rules first, policy last, plus an at rollback |
| Rules not saved | Lost on reboot | iptables-save or netfilter-persistent save |
| Trusting ufw for Docker ports | Docker bypasses ufw | Use DOCKER-USER or bind to 127.0.0.1 |
| Blocking all ICMP | Monitoring and path MTU break | Allow echo-request and keep ICMP errors |
| Forgetting IPv6 | Open path around the IPv4 rules | Save and review ip6tables too |
Quick Reference & Troubleshooting Commands
| Task | Command |
|---|---|
| List all rules | sudo iptables -L -n -v |
| List with line numbers | sudo iptables -L INPUT -n --line-numbers |
| Allow a TCP port | sudo iptables -A INPUT -p tcp --dport PORT -j ACCEPT |
| Delete by number | sudo iptables -D INPUT LINE_NUMBER |
| Save rules | sudo iptables-save | sudo tee /etc/iptables/rules.v4 |
| ufw rules with numbers | sudo ufw status numbered |
| Allow a port in ufw | sudo ufw allow PORT/tcp |
| Block outside traffic to containers | sudo iptables -I DOCKER-USER -i eth0 ! -s 10.0.0.0/8 -j DROP |
| Symptom | First command | What to look for |
|---|---|---|
| Cannot reach a service | sudo iptables -L INPUT -n -v |
A rule with the port, and rising counters |
| Locked out of SSH | Console or cloud serial access | Policy DROP with no SSH allow rule |
| Rules gone after reboot | ls /etc/iptables/ |
Missing rules.v4 or service not enabled |
| Docker port still open | sudo iptables -L DOCKER-USER -n |
No DROP rule in the chain |
| Unsure what is blocked | sudo journalctl -k | grep iptables-dropped |
Source IPs and ports in the log lines |
TipRead the ruleset top to bottom as if you were an arriving packet. Does every legitimate source match an ACCEPT before it reaches the DROP policy? This walkthrough catches most misconfigurations before they become incidents.
RememberThe first matching rule wins. An ACCEPT for port 22 at line 5 never fires if a DROP at line 3 matches first, so check the order with
--line-numbersafter every change.