Quick answer
iptables looks intimidating but the core model is simple: chains of rules, evaluated top to bottom, first match wins.
iptables looks intimidating but the core model is simple: chains of rules, evaluated top to bottom, first match wins. A small, readable ruleset beats a giant generated one.
What you need: Root access and, ideally, a second console session open before you start.
Start with sane defaults
Set INPUT and FORWARD to DROP and OUTPUT to ACCEPT. Then explicitly allow loopback, established connections, SSH, and your web ports.
Allow what you need
Open 22 (SSH), 80 and 443 (web), and anything your app genuinely requires. Refuse everything else by default.
Make it persistent
Save the rules with iptables-persistent so they survive a reboot, and always keep a separate console open while you edit.
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -A INPUT -i lo -j ACCEPT
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
apt install iptables-persistent && netfilter-persistent save
How it works, in detail
iptables evaluates rules top to bottom and uses the first match, so a policy of DROP with explicit ACCEPT rules is far safer than trying to block bad traffic piecemeal. The loopback interface must always be allowed, and the ESTABLISHED,RELATED rule is what lets replies come back without opening every port. Because rules are in memory, they vanish on reboot unless you install iptables-persistent and save them, which is the step most people forget until the box comes back up and nothing is reachable.
Common pitfalls
- Locking yourself out of SSH and having no console to fix it.
- Not saving rules, so a reboot silently wipes the firewall.
Pro tip
Always keep a second SSH session open and test connectivity in it before closing the one you edited in.
Lock yourself out exactly once and you will never again edit firewall rules without a second, out-of-band session open.



0 Comments