Friday, January 29, 2010

Port mapping in Linux in Ubuntu and CentOS

If you used to setup web servers under windows easily, you will find Linux doesn't show itself bared on the network. Indeed, Linux has its own secured solutions to let your web servers listen to the 80 port. In fact, you can not use the ports under 1024 for the individual users. Because they belongs to the super user. Moreover, its recommended to run web servers with a limited user. So, the best way to run HTTP listeners on 80 port is to map upper than 1024 ports 80 port.
Last week I worked with a JBoss application server which has ran on 8080 port. In addition, the client needed to run it on 80 port, without any modification on JBoss settings. I make it so easily by running 3 iptable commands which I found in some tutorials on the web.

sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080

sudo iptables -I INPUT -p tcp --dport 8080 -j ACCEPT

sudo iptables -t nat -A OUTPUT -o lo -p tcp --dport 80 -j REDIRECT --to-port 8080

NOTE: if you dont put -o lo option for the last command, all outgoing requestes will rout to the 8080 port on the localhost.

Finally you should save new rules into disk. below command persists changes.

sudo iptables-save > iptable.rules

Moreover you need to make sure rules will loaded in the next start up. So, add below line into /etc/network/interfaces after iface command:

pre-up iptables-restore < /etc/iptable.rules


If you are using CentOS then it is enough to run below command to persist iptables rules:

/sbin/service iptables save

Restart the network connection and enjoy it.

No comments:

Post a Comment