Basic iptables Commands Every DevOps Engineer Should Know
iptables is a powerful command-line utility for configuring the Linux kernel firewall. It is widely used for managing network traffic and securing Linux-based systems.
Why Use iptables?
- Block unwanted traffic
- Allow specific ports
- Forward or redirect traffic
- Protect services from unauthorized access
Basic iptables Syntax
iptables -[A|D|I|R|L] [CHAIN] [OPTIONS]
-A: Append a rule-D: Delete a rule-I: Insert a rule-R: Replace a rule-L: List rules
Common Chains
INPUT: Packets destined to the hostOUTPUT: Packets sent from the hostFORWARD: Packets routed through the host
Examples
List All Rules
iptables -L -v -n
Allow Incoming SSH (Port 22)
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
Drop All Incoming Traffic By Default
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
Delete a Rule
iptables -D INPUT -p tcp --dport 22 -j ACCEPT
Saving and Restoring Rules
Save Rules
iptables-save > /etc/iptables/rules.v4
Restore Rules
iptables-restore < /etc/iptables/rules.v4
Conclusion
Understanding iptables helps you take full control over traffic flow in and out of your Linux systems. These basic commands will help you secure your infrastructure and troubleshoot network issues.