How to List, Add and Delete iptables Rules on Linux
In this tutorial, you'll learn about How to List, Add and Delete iptables Rules on Linux. We cover key concepts, practical examples, and best practices.
The Problem
You need to inspect or modify the Linux netfilter firewall rules but do not know how to list iptables rules, add a new rule, or remove an existing one without disrupting active connections.
Quick Fix
List All Current iptables Rules
sudo iptables -L -v -n --line-numbers
# Chain INPUT (policy ACCEPT 1000 packets, 500K bytes)
# num pkts bytes target prot opt in out source destination
# 1 100 5000 ACCEPT all -- * * 0.0.0.0/0 0.0.0.0/0
# Chain FORWARD (policy DROP 0 packets, 0 bytes)
# Chain OUTPUT (policy ACCEPT 800 packets, 400K bytes)
Use -L to list rules, -v for verbose (packet/byte counts), -n to skip DNS resolution, and --line-numbers to show rule numbers for easy deletion.
Add a New Rule to Allow a Port
sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT
# (no output)
sudo iptables -L INPUT -n -v
# Chain INPUT (policy ACCEPT ...)
# ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:443
-A INPUT appends a rule to the INPUT chain. Use -I INPUT 1 to insert at a specific position (e.g., before a DROP rule).
Delete a Rule by Specification
sudo iptables -D INPUT -p tcp --dport 443 -j ACCEPT
# (no output)
-D deletes a rule matching the exact specification. If the rule does not exist, iptables exits with an error.
Delete a Rule by Line Number
sudo iptables -L INPUT --line-numbers -n
# Chain INPUT (policy ACCEPT)
# num target prot opt in out source destination
# 1 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:80
sudo iptables -D INPUT 1
# (no output)
Use the line number from --line-numbers with -D INPUT <num> to delete a specific rule without retyping the full specification.
Insert Rules at a Specific Position
sudo iptables -I INPUT 2 -p tcp --dport 8443 -j ACCEPT
# (no output)
Use -I INPUT <number> to insert a rule at a specific position rather than appending with -A. This is critical when you have a DROP rule at the end and need new rules to be evaluated before the drop.
Use Debug Mode for Risky Operations
# See every command before it executes
bash -x risky_script.sh
# + sudo sed -i 's/old/new/' /etc/fstab
Always use debug mode when running scripts that modify system configuration like fstab, SELinux settings, or firewall rules. This shows every command before it executes, catching typos early.
Prevention
- Always use
--line-numberswhen listing rules to simplify deletions - Save rules with
iptables-save > /etc/iptables/rules.v4after making changes - Test rules with
-I(insert) instead of appending to control rule ordering - Use
iptables -Cto check if a rule exists before adding or deleting it
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro