Iptables basics
Quick answer
Iptables is the classic rule-based Linux firewall. It ships on most distributions but starts with no rules, meaning all traffic is allowed until you add some. Use sudo iptables -L to see current rules and -I INPUT to add one at the top of the chain.
Many current distributions use nftables or a front end like UFW or firewalld by default, but the underlying iptables commands below still work on systems where iptables itself is in use. Check which firewall tool is active on your server before assuming iptables is it.
How iptables works
Iptables organises rules into chains:
- INPUT: packets destined for the host itself
- OUTPUT: packets originating from the host
- FORWARD: packets passing through the host
Two options add rules: -A (append, adds to the bottom of the chain) and -I (insert, adds at position one by default).
Basic commands
List current rules
sudo iptables -L
sudo iptables -L --line-numbersDelete a rule by line number
sudo iptables -D INPUT 2Set a chain's default policy
sudo iptables -P FORWARD DROPFlush all rules
This clears every rule in every chain. Use with care, and only once you know how you'll restore access afterwards.
sudo iptables -FSecuring your connection
Before you tighten anything, allow your own IP address on the port you connect through so you don't lock yourself out.
sudo iptables -I INPUT -p tcp -s [your public IP address] --dport 22 -j ACCEPTOpening specific ports
sudo iptables -I INPUT -p tcp --dport 22 -j ACCEPT
sudo iptables -I INPUT -p tcp --dport 80 -j ACCEPT
sudo iptables -I INPUT -p tcp --dport 443 -j ACCEPTSave and restore rules
Iptables rules don't persist across reboots on their own. How you save them depends on your distribution.
Debian and Ubuntu
sudo apt-get install iptables-persistent
sudo iptables-save > /etc/iptables/rules.v4
sudo iptables-restore < /etc/iptables/rules.v4RHEL, CentOS Stream, Rocky Linux, AlmaLinux
On current RHEL-family releases, iptables rules are typically saved through the iptables-services package rather than a plain service iptables save call. Many of these systems use firewalld by default instead, so check which is active first.
sudo iptables-save > /etc/sysconfig/iptables
sudo iptables-restore < /etc/sysconfig/iptables