iptables tutorial: configure a Linux firewall from scratch
Build a Linux firewall from scratch using iptables — learn chains, tables, rules, and NAT configuration.
- iptables tutorial: configure a Linux firewall from scratch
- What You Will Need
- Step 1: Understand the iptables Tables and Chains
- Step 2: Set the Default Policy for iptables Chains
- Step 3: Allow Established Connections and Loopback Traffic with iptables
- Step 4: Allow SSH Traffic with iptables
- Step 5: Allow HTTP and HTTPS Traffic with iptables
- Step 6: Save the iptables Rules
- Step 7: Verify the Complete iptables Ruleset
- What You Learned
iptables tutorial: configure a Linux firewall from scratch
Build a Linux firewall from scratch using iptables — learn chains, tables, rules, and NAT configuration.
What You Will Need
- A Linux server (Ubuntu 22.04+ or Debian 12+) with root or sudo access.
- No existing firewall rules (or willingness to flush them).
Step 1: Understand the iptables Tables and Chains
iptables organizes rules into tables. The
filter table (default) controls traffic acceptance and rejection. It has three chains:
INPUT (traffic destined for this host),
OUTPUT (traffic originating from this host), and
FORWARD (traffic passing through this host to another destination). Each chain evaluates rules in order — the first matching rule determines the packet's fate.
Step 2: Set the Default Policy for iptables Chains
iptables applies the default policy when no rule matches a packet. Set the default to DROP for INPUT and FORWARD, and ACCEPT for OUTPUT:
sudo iptables -P INPUT DROP
sudo iptables -P FORWARD DROP
sudo iptables -P OUTPUT ACCEPTImportant:Allow SSH before setting INPUT to DROP, or you will lose remote access.
Step 3: Allow Established Connections and Loopback Traffic with iptables
iptables should accept traffic for already-established connections and traffic on the loopback interface (127.0.0.1):
sudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
sudo iptables -A INPUT -i lo -j ACCEPTStep 4: Allow SSH Traffic with iptables
iptables accepts incoming TCP connections on port 22 for SSH access:
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPTStep 5: Allow HTTP and HTTPS Traffic with iptables
iptables opens ports 80 and 443 for web server traffic:
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPTStep 6: Save the iptables Rules
Save the rules so they persist across reboots:
sudo apt install iptables-persistent
sudo iptables-save | sudo tee /etc/iptables/rules.v4Step 7: Verify the Complete iptables Ruleset
List all rules with packet counters:
sudo iptables -L -n -vWhat You Learned
This tutorial covered iptables tables and chains (filter table with INPUT, OUTPUT, FORWARD), default policies (DROP vs ACCEPT), stateful connection tracking (
--state ESTABLISHED,RELATED), service-specific port rules, and rule persistence with
iptables-persistent.