Configuring NGINX in front of Tomcat or other Java application server

NGINX is an awesome software that functions as both web server and as a reverse proxy. Sometimes you may need to configure it in front of your tomcat or other application server. There are many reasons but here are some common ones:

  • there are many types of attacks that NGINX can handle very well. This is why it is commonly put in front of Apache for PHP websites.
  • NGINX has caching functionality that can speed up your website significantly. Perhaps 10, 100 or 1000 times faster.
  • you may need to host multiple Java application in a single server and are accessed using different domains.

I wish to expound on the last item on the list. Say for example you have 2 domains: mywallet.com and mydocuments.com. And the corresponding applications are: wallet.war and documents.war. If you wish to deploy this on a single server, you will encounter some difficulties. If you deploy it on a single Tomcat instance, both applications can be accessed with either domain name. For example, you can access your wallet and document applications through the url: mywallet.com/wallet and mywallet.com/documents. Which is ugly. A cleaner solution is to deploy each application on a different Tomcat instance, using different ports. And then put a reverse proxy in front of them.

Based on the sample above, let’s assume we configured Tomcat to use port 8080 for wallet.war and 8081 for documents.war.

Install nginx, and immediately stop the service

apt-get install nginx
service nginx stop

Create the file /etc/nginx/sites-enabled/wallet.conf and place the following contents:

server {
    server_name  mywallet.com;
    location / {
        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Server $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass http://localhost:8080;
    }
}

And then create the file /etc/nginx/sites-enabled/documents.conf and place the following contents:

server {
    server_name  mydocumens.com;
    location / {
        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Server $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass http://localhost:8081;
    }
}

And then restart nginx

service nginx restart

And you can now try to access your websites.

NGINX and Java Posts

Comments

comments