Forwarding Ports with iptables
There are situations in which network activity directed at one computer should be handled by another computer, or possibly another port on the same computer. For these tasks , iptables lets you implement port forwarding, which echoes incoming network traffic to another computer.
When to Forward Ports
Port forwarding can be an extremely useful tool in certain situations, including the following:
This last possibility is a particularly common one when running NAT. Note that this behavior degrades the security advantages of NAT, because you're effectively exposing an internal system (or at least, one of its ports) to the outside. You can also run only one internal server of a given type on its usual port in this way, at least with the IP masquerading form of NAT. (If your NAT router has two external addresses, you can forward ports on both addresses to different internal systems.) If you want to make two internal servers of the same type (such as two Web servers) available to the outside, you'll have to run one on a nonstandard port or obtain some other external IP address.
Setting iptables Port Forwarding Options
There are several different ways to enable port forwarding on a Linux system that provides NAT functions. One is to do it with iptables , using its NAT functionality. To do so, you can type a command similar to the following:
# iptables -t nat -A PREROUTING -p tcp -i external-interface \ --destination-port port-num -j DNAT --to dest-addr:port-num
Important features of this command include:
You can enter several port forwarding commands ”as many as necessary to forward any ports that handle servers you want to run internally. As with the basic NAT or firewall configuration, you can create entries in a startup script to run these commands whenever your system starts. You can then leave the configuration alone.