Skip to content
Back to posts

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.

Terminal window
sudo iptables -t nat -A PREROUTING -d 47.90.123.123 -p tcp --dport 3306 -j DNAT --to-destination 45.63.110.110:80

This 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:

Terminal window
sudo iptables -t nat -A POSTROUTING -d 45.63.110.110 -p tcp --dport 80 -j SNAT --to-source 47.90.123.123

MASQUERADE can be used instead.

List the rules. Specify the NAT table with -t; otherwise iptables displays the filter table:

Terminal window
sudo iptables -t nat -nvL --line-numbers

These 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?


Originally published on SegmentFault.

Copyright notice

Unless otherwise stated, quietin owns the copyright in all articles. All rights reserved. Except as permitted by law or with prior written permission, reproduction or republication, in whole or in part, is prohibited. Permitted quotations must credit the author and link to the original article.