Easy migration of a service to another, totally different host with iptables

July 9th, 2007 by lucas

I’m tired of googling for this every time I need it, so I’m blogging about it.

Q: How can one redirect all connections to hostA:portA to hostB:portB, where hostA and hostB and in totally different parts of the Internet?

A:
echo 1 > /proc/sys/net/ipv4/ip_forward
$IPT -t nat -A PREROUTING -p tcp --dport portA -j DNAT --to hostB:portB
$IPT -A FORWARD -i eth0 -o eth0 -d hostB -p tcp --dport portB -j ACCEPT
$IPT -A FORWARD -i eth0 -o eth0 -s hostB -p tcp --sport portB -j ACCEPT
$IPT -t nat -A POSTROUTING -p tcp -d hostB --dport portB -j SNAT --to-source hostA

Connections are masqueraded, that means that, for hostB, all connections are coming from hostA. So be careful.

Comments are closed.