How to redirect an incoming connection to a different IP address on a specific port using IPtables

Problem
Redirect traffic incoming on a specific port to a different IP address / another server

tl;dr

Step 1:

iptables -t nat -A PREROUTING -p tcp --dport 3124 -j DNAT --to-destination 1.1.1.1:3000
iptables -t nat -A POSTROUTING -j MASQUERADE

Solution

Below will show you how to redirect port 3124 on one machine to port 3000 on a different machine / IP address.
This can be useful for firewall related reasons.

iptables -t nat -A PREROUTING -p tcp --dport 3124 -j DNAT --to-destination 1.1.1.1:3000

This will route traffic incoming on port 3124 to 1.1.1.1 on port 3000.
You can put in any port or IP address you need there.

Step 2:

iptables -t nat -A POSTROUTING -j MASQUERADE

We set MASQUERADE to mask the IP address of the connecting system and use the gateway IP address instead. This is necessary for it to communicate back to the gateway, then to your client.

That is all that is required to get this to work.

Optional:

service iptables save

This will save the changes, so they are persistent after a reboot.

Author:

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.