Introduction
iptables is the historical tool for managing the netfilter firewall on Linux. It allows filtering incoming, outgoing, and transit network traffic. In 2026, even with nftables, understanding iptables remains essential for maintaining existing systems and certifications. This tutorial teaches you the basic commands to create a functional and secure firewall.
Prerequisites
- A Linux server (Ubuntu/Debian or CentOS)
- Root or sudo access
- Active SSH connection
- Basic command line knowledge
Check Current Rules
sudo iptables -L -v -nThis command displays all active chains and rules with statistics. It helps you understand the initial firewall state before making any changes.
Step 1: Prepare a Clean Firewall
Before creating new rules, it is recommended to flush existing rules to avoid conflicts.
Flush Existing Rules
sudo iptables -F
sudo iptables -X
sudo iptables -ZThese commands remove all rules, custom chains, and reset counters to zero. Always run this step first on a new server.
Set Default Policies
sudo iptables -P INPUT DROP
sudo iptables -P FORWARD DROP
sudo iptables -P OUTPUT ACCEPTReject all incoming and forwarding traffic by default. Only explicitly allowed connections will pass. Outbound traffic remains open to allow updates.
Step 2: Allow Essential Connections
A server needs to accept SSH traffic and sometimes HTTP/HTTPS. We will create precise rules.
Allow SSH and HTTP
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPTThese rules accept TCP connections on ports 22 (SSH), 80 and 443 (web). Always place ACCEPT rules before the DROP policy.
Allow Loopback and Established Connections
sudo iptables -A INPUT -i lo -j ACCEPT
sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPTLoopback is essential for proper system operation. The conntrack rule allows already established connections to continue without blocking.
Best Practices
- Always test rules via a parallel SSH session before making them persistent
- Use comments with -m comment
- Save rules after validation
- Expose the minimum number of ports
- Document every added rule
Common Mistakes to Avoid
- Blocking the SSH port and losing server access
- Forgetting to save rules after reboot
- Creating contradictory rules without logical order
- Not enabling the conntrack module for existing connections
Going Further
Discover our complete training on Linux security and modern firewalls: https://learni-group.com/formations