Tomcat/Glassfish/Jetty on Port 80 with IPTables

If you – like me – have the problem, that you need to run Tomcat or Glassfish or any other Java Webserver on Port 80, this might come handy for you:

The problem:
Tomcat, Jetty, Glassfish, JBoss AS etc. .. they all run on unprivileged ports > 1024, defaulting to 8080.

If you want to run them on port 80, you have several choices:
– front them with Apache
– front them with Squid
– use some tools like authbind, etc.
– use IPTables magic (which we will describe here)

Primitive IPTables solution:
This solution comes from the blog entry ” Installing Tomcat on port 80 with iptables
You have to compile NAT support into your kernel and use an iptables rule like this one

iptables -t nat -I PREROUTING --src 0/0 --dst $yourip -p tcp --dport 80 -j REDIRECT --to-ports 8080

which redirects all incoming traffic on port 80 on $yourip (e.g. 74.125.39.99) to port 8080 on the local machine.
If your webserver listens only to 127.0.0.1 this is all you need to be save.

However, I have a bit a different setup:

– Two networks with different providers (4mbit e.g. 74.125.39.99, 12mbit e.g. 98.137.149.56 )
– Two servers, one of them quite small powered (pentium4 on the 4mbit line), the other quite strong (dual quad core 2ghz on the 12mbit line)
– Glassfish on the strong server
– DNS load balancing for the domain
– both servers should map to the same glassfish instance.
– the servers are connected through a direct link with private IP-addresses (10.x.x.x range)
– Glassfish binds only to the private IP-Address of the strong server, meaning 10.0.100.10:8080
– both 74.125.39.99:80 and 98.137.149.56:80 should redirect the traffic to 10.0.100.10:8080

Here’s how I’ve done it (I got some inspiration from this linux questions forum entry):

On the “strong” server

#this forwards traffic to the internal ip
iptables -A PREROUTING -t nat -d 74.125.39.99/32 -p tcp -m tcp --dport 80 -j DNAT --to 10.0.100.10:8080
#this allows traffic on the external interface on port 80
iptables -A INPUT -d 74.125.39.99/32 -p tcp -m tcp --dport 80 -j ACCEPT
#this allows traffic on the internal ip on port 8080
iptables -A INPUT -d 10.0.100.10/32 -p tcp -m tcp --dport 8080 -j ACCEPT

nearly the same on the “weaker” server

#this forwards traffic to the internal ip
iptables -A PREROUTING -t nat -d 74.125.39.99/32 -p tcp -m tcp --dport 80 -j DNAT --to 10.0.100.10:8080
#this allows traffic on the external interface on port 80
iptables -A INPUT -d 98.137.149.56/32 -p tcp -m tcp --dport 80 -j ACCEPT

That’s it!

Perfectly save, perfectly scalable glassfish v3 (no apache bottleneck in your comet apps!)

Join the Conversation

1 Comment

Leave a comment

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