Ran into this one today for a client and it has been such a long time since I had to do any NAT routing with iptables, it took me a bit to suss it out again how it was done properly. In light of that, documenting it here so it is easier to find 5 years from now when I need to do it again. 😉
Set forwarding in sysctl.cnf:
net.ipv4.ip_forward = 1
Then set the two rules. One to route the traffic to the remote host and the other to route it back:
# iptables -A PREROUTING -t nat -p tcp -d ip.of.box.1 –dport 3306 -j DNAT –to-destination ip.of.box.2
# iptables -A POSTROUTING -t nat -p tcp -d ip.of.box.2 –dport 3306 -j SNAT –to-source ip.of.box.1
Presto! All traffic to “ip.of.box.1” on port 3306 is now being routed out to 3306 on “ip.of.box.2”.