Understanding iptables: The Linux Firewall Explained
iptables is the classic tool for configuring the Linux kernel's built-in firewall (netfilter). It decides which network packets your server accepts, drops or forwards. It looks intimidating at first, but the mental model is simple once you understand three concepts: tables, chains and rules.
The mental model
- Tables group rules by purpose. The one you'll use most is
filter(allow/deny traffic). Others includenat(address translation) andmangle. - Chains are points where rules are checked. In the filter table:
INPUT(traffic to the server),OUTPUT(traffic from it), andFORWARD(traffic routed through it). - Rules match packets (by port, protocol, source IP…) and take a target:
ACCEPT,DROPorREJECT.
Packets flow through a chain top to bottom; the first matching rule wins. If nothing matches, the chain's policy applies.
Viewing current rules
sudo iptables -L -n -v --line-numbersA safe starter firewall
The goal: allow SSH, HTTP and HTTPS, allow established connections and loopback, and drop everything else. Build the rules before changing the default policy so you don't lock yourself out.
# Allow loopback and already-established connections
sudo iptables -A INPUT -i lo -j ACCEPT
sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
# Allow SSH, HTTP, HTTPS
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT
# Allow ping (optional)
sudo iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT
# Now set default policies: drop incoming, allow outgoing
sudo iptables -P INPUT DROP
sudo iptables -P FORWARD DROP
sudo iptables -P OUTPUT ACCEPTBlocking and rate-limiting
# Block an abusive IP
sudo iptables -I INPUT -s 203.0.113.42 -j DROP
# Rate-limit new SSH connections to slow brute force
sudo iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW \
-m recent --set --name SSH
sudo iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW \
-m recent --update --seconds 60 --hitcount 5 --name SSH -j DROPMaking rules persist
iptables rules are lost on reboot unless you save them:
sudo apt install iptables-persistent
sudo netfilter-persistent saveA word on nftables
Modern distributions are moving to nftables as the successor to iptables, with a cleaner syntax. The iptables command still works (often as a compatibility layer), and the concepts transfer directly. If you're starting fresh on a very recent distro, it's worth learning nftables too — but iptables knowledge remains widely applicable. If the raw syntax feels error-prone, a front-end like Shorewall or ufw makes it far more manageable.