iptables – port forwarding

My linux gateway server is the only one visible to the internet, while all other machines are in an internal subnet not visible to the outside internet, but can access the outside net using Iptables based Network Address Translation (NAT).

In this setup if I want to run a public service like httpd, not on the gateway server ( where it is visible to outside ) but on an internal machine ( which is not visible outside ) how do I make it available to the outside internet.To make the above scenario of exposing and internal machine’s service to outside we need to use port forwarding on the gateway server. Which is assigning a port on the gateway to accept all connections and forward it to the internal machines port where the service is listening to.

Let x.x.x.x be the IP address of the gateway server connected to the cable modem and , the IP address of the internal machine. And say we want to run a web server ( httpd ) on 192,168.0.2 on port 80 which should be avaialble to the outside internet. We can forward the port 80 on xxx.xxx.xxx.xxx to port 80 of

Source: xxx.xxx.xxx.xxx:80 — forwarded to ->

Port Forwarding using Iptables
First set the rule,

iptables -t nat -A PREROUTING -p tcp -i eth1 –dst [public IP] –dport 80 -j DNAT –to-destination

-t, table
-A, Append rule to end of a chain
PREROUTING, a pre-defined “chain” rule available with iptables
-p, protocol
-i, Match “input” interface on which the packet enters
-o, Match “output” interface on which the packet exits
–dst, The flag –dst is an alias for the option -d
–dport, Tcp destination port
-j, Jump to the specified target chain when the packet matches the current rule
DNAT, Valid in POSTROUTING chain. Output
–to-destination, Destination address of packet

To view the rules applied with NAT tables –

iptables -t nat -vnL –line

Now to finally port forwarding –

iptables -I FORWARD 3 -o eth1 -s -j ACCEPT

Here 3 means line number three or rule three on NAT list

To delete an existing rule –

iptables -t nat -D PREROUTING 4

Here, 4 means line number 4 on NAT table.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: