Implement Apache Tomcat Load Balancing for Java Web Application with Nginx in a Linux Environment.

Iroshan Aberathne
3 min readMay 22, 2021

This article will demonstrate the configuration steps to implement multiple tomcat servers with Nginx load balancer.

Nginx Load Balancer

Setup Multiple Tomcat Instances.

  1. Download tomcat and extract it to make two folders called instance-01 and instance-02 as shown in following figure.
Two Tomcat Server Instances

2. Then go to the server.xml file which is available in /conf folder to configure the tomcat running ports. Refer to the following images to do the configuration in both instances.

Tomcat Instance One
Tomcat Instance Two

3. Copy the same Java web application (.war file, in this article I have created DM.war) to /webapps folder in both instances then start each instance with ./startup.sh file which is in /bin folder.

Start Tomcat Servers

Install and Configure Nginx

  1. Install Nginx in ubuntu

sudo apt update

sudo apt install nginx

sudo ufw enable (if disable — sudo ufw status )

sudo ufw app list (output would be : Nginx Full, Nginx HTTP, Nginx HTTPS etc)

sudo ufw allow ‘Nginx HTTP’

sudo status nginx

Nginx Status

2. Configure Two tomcat instance in to Nginx : go to /etc/nginx

3. Open nginx.conf with sudo nano nginx.conf (if nano is not available please install it or use other tool) and enter following lines in to this file.

Edit view

log_format upstreamlog ‘$server_name to: $upstream_addr {$request} ‘
‘upstream_response_time $upstream_response_time’
‘ request_time $request_time’;

This is to enable to logs for upstream.

upstream tomcatdev {
ip_hash;
server localhost:8081;
server localhost:8082;
}

This is the place where we configure our local tomcat instances. You can use any name for “tomcatdev”. The ‘ip_hash’ ensures that request with a particular IP always go to the same tomcat instance.

server {
listen 8080;
server_name localhost;
access_log /var/log/nginx/nginx-access.log upstreamlog;
location / {
proxy_pass http://tomcatdev;
}
}

Nginx running on localhost(server_name) port 8080(listen) (can change). ogs will be saved to access_log /var/log/nginx/nginx-access.log upstreamlog; “. In order to show the available tomcat instance and its urls this code block is used where ‘tomcatdev’ is a reference name.

location / {
proxy_pass http://tomcatdev;
}

Finally you have to un-comment ‘server_names_hash_bucket_size 64;’ which is in same file.

Then save the file with ctrl+o command and exit from the file with ctrl+x command.

You can verify whether file is successfully updated with this command -> sudo nginx -t

Then start the Nginx with following command

sudo systemctl start nginx

Testing Load Balancer

In the web access with http://localhost:8080/DM. Then see the log file available in this path : sudo cat /var/log/nginx/nginx-access.log

Log

You can see that Nginx load balancer is working !!!!!!

--

--