iptables and nftables
Netfilter chains (INPUT/OUTPUT/FORWARD/PREROUTING/POSTROUTING), tables (filter/nat/mangle), rule evaluation order, and nft syntax.
Overview
Overview iptables and nftables are the primary tools for configuring the Linux kernel's packet filtering framework, Netfilter. Every major Linux firewall, container networking system, and cloud hypervisor ultimately uses Netfilter under the hood — Docker, Kubernetes (kube-proxy), and UFW all write iptables rules or nftables rules.
Netfilter uses the concept of tables and chains. The filter table handles allow/drop decisions. The nat table handles Network Address Translation (SNAT, DNAT, masquerade). The mangle table modifies packet headers (TTL, DSCP, marks). The raw table is evaluated first and can exempt packets from connection tracking.
Within each table, chains represent hook points in the packet processing path. The INPUT chain processes packets destined for the local machine. The OUTPUT chain processes packets originating from the local machine. The FORWARD chain processes packets being routed through the machine. The PREROUTING chain is evaluated before routing decisions — this is where DNAT happens. The POSTROUTING chain is evaluated after routing decisions — this is where SNAT and masquerade happen.
Rules within a chain are evaluated sequentially from top to bottom. The first matching rule applies its target (ACCEPT, DROP, REJECT, LOG, DNAT, SNAT, RETURN, a user-defined chain). If no rule matches, the chain's default policy applies.
nftables replaced iptables as the default in most Linux distributions starting around kernel 5.2. nftables has a cleaner syntax, a single binary (nft) replacing iptables/ip6tables/arptables/ebtables, atomic rule replacement, and better performance for large rulesets.
Key concepts
- Tables
- Chains
- Rule evaluation order
- Connection tracking (conntrack)
- DNAT and SNAT
- nftables
Interview questions
- Walk through how iptables processes a packet and explain the table and chain evaluation order.
- Write a minimal iptables ruleset for a web server that allows SSH, HTTP, HTTPS, and established traffic, and drops everything else.
- How does Docker use iptables, and why should you never flush all iptables rules on a Docker host?
Sign up free to read the full topic
More Networking topics
Start free on Cariara · Coding problems · System design studio