How to Port Forward using netfilter/iptables

June 21, 2011

This is a quick example of how to write a quick bash script to use iptables to configure netfilter for port forwarding purposes. This sometimes comes in handy if you need to forward a non standard service/port through a standard port, also a slew of other use cases.

Below is an example bash script port forwarding on eth0 for IP destination tcp port 80 to tcp port 123 as well as tcp port 443 to tcp port 123

/sbin/iptables -F
/sbin/iptables -t nat -A PREROUTING -p tcp -i eth0 -d --dport 80 -j DNAT --to
/sbin/iptables -t nat -A PREROUTING -p tcp -i eth0 -d --dport 443 -j DNAT --to
/sbin/iptables -A FORWARD -p tcp -i eth0 -d --dport 123 -j ACCEPT

*Make sure the iptables service is started, then run the script

*Beware /sbin/iptables -F will flush your existing rules if you have any so make sure you run
/sbin/iptables -L -v -n –line-numbers and see. If you have any rules add them to the script.

*If you are using a different src and dst IP you will want to enable ip forwarding:
echo 1 > /proc/sys/net/ipv4/ip_forward

Comments for “How to Port Forward using netfilter/iptables”

  1. Matt commented on June 20, 2013

    To make this work, I needed to add
    iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

  2. Ian commented on May 8, 2014

    Hi all
    Yes I had to put in a POSTROUTING rule as well, then it worked ok.
    This is strange, because the majority of tutorials don’t mention that.

    This means (I assume), there’s something going on I don’t understand with iptables.


Leave a Reply