A hands-on guide to write and apply basic iptables firewall rules that protect SSH and web services. 16.11.2025 | reading time: 3 min You run a small Linux server and need to block unwanted traffic while keeping SSH and web services reachable; iptables is the command-line tool to implement those rules directly in the kernel packet filter. Practical example: a hardened small server Follow these commands to immediately apply a minimal, stateful policy that allows loopback, established traffic, SSH and web ports while dropping other incoming connections: ```# flush and set default policies iptables -F iptables -X iptables -t nat -F iptables -t nat -X iptables -P INPUT DROP iptables -P FORWARD DROP iptables -P OUTPUT ACCEPT # allow loopback and established connections iptables -A INPUT -i lo -j ACCEPT iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT # allow SSH and web (NEW connections) iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -j ACCEPT iptables -A INPUT -p tcp --dport 80 -m conntrack --ctstate NEW -j ACCEPT iptables -A INPUT -p tcp --dport 443 -m conntrack --ctstate NEW -j ACCEPT # optional: allow ping iptables -A INPUT -p icmp -m icmp --icmp-type 8 -j ACCEPT # show active rules iptables -L -n -v ``` Example of the last command output (abbreviated): ```Chain INPUT (policy DROP 0 packets, 0 bytes) pkts bytes target prot opt in out source destination 150 12K ACCEPT all -- lo * 0.0.0.0/0 0.0.0.0/0 1020 80K ACCEPT all -- * * 0.0.0.0/0 0.0.0.0/0 ctstate RELATED,ESTABLISHED 10 100 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:22 5 300 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:80 ``` Why order, state and tables matter iptables evaluates rules top-to-bottom and across tables (filter, nat, mangle, raw); place broad drops after specific accepts, use the conntrack/state match for reliable stateful filtering, and remember IPv6 needs ip6tables; for persistent rules use `iptables-save` and restore with `iptables-restore` or a distribution persistence tool. Other useful features and use cases Beyond a simple server firewall, use logging (`-j LOG`) for debugging, rate-limit connection attempts (`-m limit` or `hashlimit`) to mitigate brute force, create per-interface rules for multi-homed hosts, and use NAT in the nat table for simple gateway scenarios. Related tools to know Modern distributions offer higher-level frontends and successors: nftables is the replacement for iptables, ufw and firewalld provide simpler host-level management, and tcpdump helps inspect packets while you tune rules. Next steps and certification Practice on a disposable VM, script rule sets for repeatability, and explore iptables-save plus distro-specific persistence; to deepen system knowledge consider certifications such as CompTIA Linux+ or LPIC-1 and intensive exam prep at bitsandbytes.academy. Join Bits & Bytes Academy First class LINUX exam preparation. security network utilities scripting