Simple way to remove Iptables rules on Linux command line

Let’s assume that that you are playing with iptables and wish to remove rules which are no longer valid, required or incorrect. One way of accomplishing this task would be to save all rules using iptables-save command, open the output file, remove all rules and use iptables-restore to apply new rules. Another and perhaps easier way is to list all available rules along with rule line numbers. For example:

# iptables -L --line-numbers
Chain INPUT (policy ACCEPT)
num  target     prot opt source               destination         

Chain FORWARD (policy ACCEPT)
num  target     prot opt source               destination         
1    DROP       all  --  anywhere             10.0.0.0/8          
2    DOCKER     all  --  anywhere             anywhere            
3    ACCEPT     all  --  anywhere             anywhere             ctstate RELATED,ESTABLISHED
4    ACCEPT     all  --  anywhere             anywhere            
5    ACCEPT     all  --  anywhere             anywhere            

Chain OUTPUT (policy ACCEPT)
num  target     prot opt source               destination         

Chain DOCKER (1 references)
num  target     prot opt source               destination         
1    ACCEPT     tcp  --  anywhere             172.17.0.3           tcp dpt:https
2    ACCEPT     tcp  --  anywhere             172.17.0.4           tcp dpt:http
3    ACCEPT     tcp  --  anywhere             172.17.0.5           tcp dpt:4000
4    ACCEPT     tcp  --  anywhere             172.17.0.7           tcp dpt:mysql
5    ACCEPT     tcp  --  anywhere             172.17.0.7           tcp dpt:http
6    ACCEPT     tcp  --  anywhere             172.17.0.6           tcp dpt:3142

Note, the line numbers on the left column. Now that we have all line numbers we can remove any of the iptables listed rules. For example to remove:
1 DROP all -- anywhere 10.0.0.0/8 we first need to take a note of the iptables chain name, which in this case is FORWARD and the rule number which is 1. To remove this rule we enter a following iptables command:

# iptables -D FORWARD 1


Comments and Discussions
Linux Forum