patternbashMajor
iptables Basics: Chains, Rules, and Persistence
Viewed 0 times
iptablesfirewallINPUTDROPACCEPTconntrackiptables-saverules
linux
Error Messages
Problem
iptables rules are added correctly but disappear on reboot, or rules block traffic unexpectedly because the chain traversal order is misunderstood.
Solution
Understand the INPUT/OUTPUT/FORWARD chain order and persist rules with iptables-save.
# View current rules with line numbers
iptables -L -n -v --line-numbers
# Allow established/related connections (essential)
iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
# Allow SSH
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
# Allow HTTP/HTTPS
iptables -A INPUT -p tcp -m multiport --dports 80,443 -j ACCEPT
# Drop everything else (add last)
iptables -A INPUT -j DROP
# Insert rule at specific position
iptables -I INPUT 3 -p tcp --dport 8080 -j ACCEPT
# Save rules (Debian/Ubuntu)
iptables-save > /etc/iptables/rules.v4
# Restore on boot — install iptables-persistent
apt-get install iptables-persistentWhy
iptables rules are processed top-to-bottom in each chain. The first matching rule wins. Rules are held in kernel memory and are lost on reboot unless explicitly saved. nftables is the modern replacement but iptables remains widely used.
Gotchas
- Adding a DROP rule before allowing ESTABLISHED connections will break existing SSH sessions.
- iptables-save/restore must be run as root and the iptables-persistent package must be installed for auto-restore.
- IPv6 rules require ip6tables — iptables only covers IPv4.
- Docker and Kubernetes inject their own iptables rules — manual rules can conflict with them.
Revisions (0)
No revisions yet.