Skip to main content

Configuring Linux Firewalls with iptables and ufw

Configure a default-deny Linux firewall with iptables and ufw. Protect SSH, fix the Docker and ufw bypass, and persist rules across reboots.

30 Terms

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.

flowchart TD A([Packet arrives on NIC]) --> B[PREROUTING
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:

◈ DIAGRAM
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
Remember

iptables 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
Bash
sudo iptables -L -n -v
# One chain, with line numbers for later deletes
sudo iptables -L INPUT -n -v --line-numbers
# Default policies
sudo 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 -v
Milestone 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.

Bash
# Safety net: flush rules and reopen the policy in 5 minutes
echo 'iptables -P INPUT ACCEPT; iptables -F INPUT' | sudo at now + 5 minutes
Bash
# 1. Allow replies to connections this server started
sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
# 2. Allow loopback so local services can talk to each other
sudo iptables -A INPUT -i lo -j ACCEPT
# 3. Allow SSH from the internal network only
sudo iptables -A INPUT -p tcp --dport 22 -s 10.0.0.0/8 -j ACCEPT
# 4. Allow HTTP and HTTPS from anywhere
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT
# 5. Allow the application port from the internal network only
sudo iptables -A INPUT -p tcp --dport 4000 -s 10.0.0.0/8 -j ACCEPT
# 6. Allow ping for monitoring
sudo iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT
# 7. Log what is about to be dropped, rate limited
sudo iptables -A INPUT -m limit --limit 5/min -j LOG --log-prefix "iptables-dropped: "
# 8. Set default policies LAST
sudo iptables -P INPUT DROP
sudo iptables -P FORWARD DROP
sudo iptables -P OUTPUT ACCEPT
# Verify, then open a second SSH session to confirm you can still log in
sudo iptables -L INPUT -n -v --line-numbers

Once the second session works, cancel the rollback with atq to list the job and sudo atrm JOB_ID to remove it.

Common Mistake

Setting iptables -P INPUT DROP before 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.

Security

Keep 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
Bash
# Insert at the top so a specific IP is matched first
sudo iptables -I INPUT 1 -p tcp --dport 22 -s 203.0.113.10 -j ACCEPT
# Delete by line number or by exact specification
sudo iptables -D INPUT 3
sudo iptables -D INPUT -p tcp --dport 80 -j ACCEPT
# Replace the rule at position 2
sudo 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 ACCEPT
echo $?

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
Bash
# Debian and Ubuntu: iptables-persistent
sudo apt install iptables-persistent
sudo iptables-save | sudo tee /etc/iptables/rules.v4
sudo ip6tables-save | sudo tee /etc/iptables/rules.v6
# Restore manually if needed
sudo iptables-restore < /etc/iptables/rules.v4
# RHEL, CentOS, Amazon Linux: iptables-services
sudo yum install iptables-services
sudo systemctl enable --now iptables
sudo service iptables save
# Saved to /etc/sysconfig/iptables

After 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.

Bash
sudo ufw status verbose
# Defaults
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw default deny routed
# Allow SSH from the internal network, then web traffic
sudo ufw allow from 10.0.0.0/8 to any port 22 proto tcp
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
# Application port from the internal network only
sudo 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 on
sudo ufw enable
# Review and remove by number
sudo ufw status numbered
sudo ufw delete 3

ufw 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.

Bash
# See Docker's rules
sudo iptables -L DOCKER -n -v
sudo iptables -L DOCKER-USER -n -v
# Allow replies first, otherwise the block below also cuts container return traffic
sudo iptables -I DOCKER-USER -m conntrack --ctstate ESTABLISHED,RELATED -j RETURN
# Then drop anything arriving on eth0 from outside the internal network
sudo iptables -I DOCKER-USER 2 -i eth0 ! -s 10.0.0.0/8 -j DROP

The preferred fix is to publish only on localhost and put a reverse proxy in front:

Bash
# Reachable from the world
docker run -d -p 80:80 nginx
# Reachable only from this host
docker run -d -p 127.0.0.1:8080:80 nginx
Tip

DOCKER-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.

Remember

Setting "iptables": false in /etc/docker/daemon.json stops 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.

  1. Use default-deny for incoming traffic and allow only what each server must serve.
  2. Restrict SSH to a VPN or office CIDR, and add ufw limit or fail2ban for anything public.
  3. Log before the default drop, with a rate limit so logs do not fill the disk.
  4. Save rules after every change, and keep IPv4 and IPv6 policies aligned.
  5. Test from another network with nmap -Pn 10.0.1.50 or 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
Tip

Read 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.

Remember

The 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-numbers after every change.

Resources

Explore More in Linux Networking and Security

All 4 Topics

Frequently Asked Questions

Is Configuring Linux Firewalls with iptables and ufw free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Configuring Linux Firewalls with iptables and ufw topic cover?

Configure a default-deny Linux firewall with iptables and ufw. Protect SSH, fix the Docker and ufw bypass, and persist rules across reboots.

Found a mistake, an outdated step or a broken link?