How To Port Forward (redirect traffic destined for an IP address to a specific port)

Scenario:  On a Linux server, it can be useful to send traffic destined to a certain IP address to a different port on the server.  The listening service could be unique insofar as its port number has been designated.  The listening service could be a Docker container or a guest virtual machine.
Method:  iptables -t nat -A PREROUTING -i eth3 -p tcp --dport 80 -j DNAT --to 91.91.91.91:81
Explanation:  The interface receiving the HTTP requests (port 80) is eth3.  80 is the port that the server can listen on (for packets destined to eth3).  The routing that this command will produce will be to redirect the traffic to 91.91.91.91 over port 81.   Change the interface name (eth3), the d(estination) port value, the IP address or the final port number as needed.  This is an inbound rule so there are, in a way, two destination ports (80 for listening and 81 for somewhere else on the server).  For future reference, the --sport flag is a designation of a source port for IP tables commands.  NAT (network address translation) can work with mapping two different IP addresses or with mapping sockets (IP addresses bound to port numbers).

Leave a comment

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