Forwarding Traffic with iptables
A practical iptables setup for relaying TCP connections through an intermediate server with DNAT and SNAT rules.
Why: A direct connection is sometimes slow while a relayed connection is fast; network routing in China can be complicated.
Use case: If you have multiple VPS instances, they can relay traffic for one another and work around IP-based regional restrictions.
This is simply remote port forwarding. It is the simplest solution I know—just a few commands, without HAProxy or Socat. It can also forward several external ports into one Shadowsocks port, avoiding multiple Shadowsocks processes.
This note does not explain iptables fundamentals.
Goal: Relay requests sent to 47.90.123.123:3306 onward to 45.63.110.110:80.
sudo iptables -t nat -A PREROUTING -d 47.90.123.123 -p tcp --dport 3306 -j DNAT --to-destination 45.63.110.110:80This adds a rule to the NAT table and rewrites the destination for outbound traffic.
For the return path, rewrite the source IP to the relay machine’s 47.90.123.123:
sudo iptables -t nat -A POSTROUTING -d 45.63.110.110 -p tcp --dport 80 -j SNAT --to-source 47.90.123.123MASQUERADE can be used instead.
List the rules. Specify the NAT table with -t; otherwise iptables displays the filter table:
sudo iptables -t nat -nvL --line-numbersThese rules exist only in memory and disappear after a reboot. For persistent rules on Ubuntu, see the official IptablesHowTo.
There is still a potential problem with this setup. Did you spot it?