IPTables allows you to easily setup rules for packet filtering/forwarding.
So, to keep it short and simple: assume you’d like to forward any traffic coming to your machine (192.168.0.1) on port 80 to machine2 (192.168.0.2) on port 8080 then:
– Enable port forwarding:
echo 1 > /proc/sys/net/ipv4/ip_forward
– Now add the rules:
iptables -t nat -A PREROUTING -p tcp -d 192.168.0.1 –dport 80 -j DNAT –to 192.168.0.2:8080
iptables -t nat -A POSTROUTING -d 192.168.0.2 -j MASQUERADE
The -p tcp flag specifies that the protocol is TCP (as opposed to UDP, ICMP for example).
The -d 192.168.0.1 flag specifies that the packets was destined to IP 192.168.0.1
The –dport 80 means that the packet had port 80 as destination
-j is the target of the rule being enforced, NAT (network address translation). In more advanced rules, one can specify a predefined iptables chain of rules.
–to will specify to where this packet should be forwarded, and on which port
As for the second rule, it says that outgoing packets to the second machine should be masqueraded. In other terms, the user trying to access the original machine on port 80 will not have a feel that his request was forwarded. The packet will show up as if it came from the masquerading host, while in practice, the request was forwarded to machine2, and the reply came back from that same machine.
On a side note, make sure to add these iptables rules to a file, give it an execution permission (chmod +x /path/to/file), and add it to /etc/rc.local so that it is executed on every system boot. Otherwise, the above rules will be fliushed every time your system is restarted.