Perfect Cheat Sheet for Port Forwarding with iptables


For example, we assume that the packets received at the Node A’s interface “" will be forwarded from another interface “" to the destination Node B “".

Forward From Node A ( to Node B (

In the following example, all packets coming to ports 31000 – 31999 are forwarding to the same ports of Node B.

iptables -t nat -I PREROUTING -p tcp -m tcp --dst --dport 31000:31999 -j DNAT --to-destination	
iptables -t nat -A POSTROUTING -m tcp -p tcp --dst --dport 31000:31999 -j SNAT --to-source
iptables -A FORWARD -m tcp -p tcp --dst --dport  31000:31999 -j ACCEPT

If you want to do same things about udp packets, replace “tcp" to “udp" on above commands.

Allow Input Packets

Also, you need to allow those input packets.

##COMMON Allow input packets to 31000:31999 ports
iptables -A INPUT -p tcp -m multiport --dports 31000:31999 -j ACCEPT
iptables -A INPUT -p udp -m multiport --dports 31000:31999 -j ACCEPT

Allow Return Packets (Opposite Direction)

In some cases, you need to allow return packets.

iptables -A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT

How To Delete iptables’ Entries

If you add wrong entries to the iptables, you can delete them with the following steps.

Step 1. Check rule number.

iptables -L --line-numbers

Result example: You can see the rule number at the left of each entry.

$ iptables -L --line-numbers
Chain INPUT (policy ACCEPT)
num  target     prot opt source               destination
1    ACCEPT     tcp  --  anywhere             anywhere             multiport dports 31000:34000
2    ACCEPT     udp  --  anywhere             anywhere             multiport dports 31000:34000

Chain FORWARD (policy DROP)
num  target     prot opt source               destination
1    DOCKER-USER  all  --  anywhere             anywhere
2    DOCKER-ISOLATION-STAGE-1  all  --  anywhere             anywhere
3    ACCEPT     all  --  anywhere             anywhere             ctstate RELATED,ESTABLISHED
4    DOCKER     all  --  anywhere             anywhere
5    ACCEPT     all  --  anywhere             anywhere
6    ACCEPT     all  --  anywhere             anywhere
7    ACCEPT     all  --  anywhere             anywhere             ctstate RELATED,ESTABLISHED
8    DOCKER     all  --  anywhere             anywhere
9    ACCEPT     all  --  anywhere             anywhere
10   ACCEPT     all  --  anywhere             anywhere
11   ACCEPT     tcp  --  anywhere             node_b               tcp dpts:31000:31999
12   ACCEPT     udp  --  anywhere             node_b               udp dpts:31000:31999

Step 2. By using the rule number, delete a rule.


Example: Delete 11th rule at the “FORWARD" chain.

iptables -D FORWARD 11