February 21, 2010

Configure Apache Web Server as Reverse Proxy in front of a Tomcat or J2EE Container

One production like scenario when using SSL or load balancing is to use a Apache Web Server in front of a Java Web Container or J2EE Container. There are two ways to make the Apache Web Server and the behind Java container – mod_proxy or mod_jk. In this blog I will show you how to use the mod_proxy alternative, acting as a reverse proxy. I will also use Ubuntu to show you how easy there is to install software on Ubuntu with Synaptic Package Manager.

The first thing to do is to install Apache Web Server and the Tomcat Container.

$ sudo apt-get install apache2 tomcat6


After installing the above software you can use the apache2ctl command to view the active sites configuration

$ sudo apache2ctl -S


or you can also list the files in /etc/apache2/sites-enabled

$ ls -al 
lrwxrwxrwx 1 root root   26 2010-02-19 07:34 000-default -> ../sites-available/default 


Before continue you can also check that everything is working by open a web browser and open http://localhost/ (Apache Web Server) and http://localhost:8080/ (Tomcat)

Now we go ahead and creating a new virtual host that is going to act as reverse proxy.

$cd /etc/apache2/sites-available 
$ sudo gedit customerapp


<virtualhost *:80="">
    ServerName customerapp.msc.se
    ServerAlias *.customer.msc.se
    ProxyRequests Off
    <proxy *="">
        Order deny,allow
        Allow from all
    </proxy>
    ProxyPass / http://localhost:8080/examples/
    ProxyPassReverse / http://localhost:8080/examples/
</virtualhost>


After creating the new site we need to link it from sites-enabled, either use ln -s or you can use the apache tool – a2ensite.

$ sudo a2ensite customerapp


With the configuration in place, you need to separate the virtual host in customapp and default. For a locale environment you can separate them by using different IP – 127.0.0.1 and your computer IP.

<virtualhost 192.168.1.4:80="">
<virtualhost 127.0.0.1:80="">


The last thing before restarting the Apache Web Server is to install proxy and proxy_http modules you can do that with the Apache tool a2enmod

$ sudo a2enmod proxy
$ sudo a2enmod proxy_http


And finally you need to restart the Apache Web Server.

$ sudo /etc/init.d/apache2 restart

No comments: