How to Setup Tomcat Clustering in Linux Tutorial (Step by Step)

How to Setup Tomcat Clustering in Linux (Tutorial). In this post, we will introduce Apache Tomcat, its advantages, then show you how to set up Tomcat Clustering on Linux.

Tomcat Clustering is a group of servers that communicate with one another. It is very useful in the case where you have hundreds of web requests per second on a routine basis.

Do you have difficulty choosing an appropriate Java server? Are you feeling less confident about the stability and flexibility of the Java server you own? Fortunately there is a solution in the name of Apache Tomcat.

Shall we start on how to How to Setup Tomcat Clustering in Linux (Tutorial)?

What Is Apache Tomcat?

Apache Tomcat is an open source Java servlet container that primarily focuses on implementing multiple Java Enterprise Specs, such as Java Server Pages, Websites API, and Java Servlet. Developed in 1998, this server’s initial objective is to host and deploy the Java servlet. It is a server side Java code used for managing HTTP results from client applications built.

Since it acts as a web server instead of a full fledged application server that constitutes data persistence and load balancing capabilities. Moreover, it provides you with the basic features of web server processing for the relevant servlets. Tomcat is designed to support the Java servlet lifecycle, such as init(), service() and destroy() phases. Developers mostly prefer this web server software for Java implementations.

Features Of Apache Tomcat

Apache Tomcat provides you with the following features:

  • Uses a nonce to prevent cross site request forgery (CSRF) attacks.
  • Includes memory leak detection and prevention.
  • Effortless in being embedded in your application.
  • Changes the ‘jsessionid’ on authentication to prevent session fixation attacks altogether.
  • Uses ‘aliases’ to store static content outside the war file.

Advantages of Apache Tomcat

The benefit of Apache Tomcat to its users happen in following ways:

Open Source Application – As discussed above, Apache Tomcat is an open source application that was released with a general public license. It enables everyone to access the core file for developing personal or commercial applications using the software. 

Lightweight – For developing an enterprise level application, it is significant to have a lightweight application to help the process run seamlessly. And Tomcat is what you need. It is lightweight and provides more flexibility in the development process. The tool also delivers faster data processing power to deploy the content effortlessly. It is a way of technology when compared to its competitors.

Flexible – The Apache Tomcat server application contains built in customization options, whose extensions provide significant benefits in developing the application. Since it is lightweight in nature, it offers more flexibility. This way, users can run the application differently to fulfil their requirements. You can tweak the application the way you want and see it perform appropriately and generate the best results.

Well Documented – Apache Tomcat is a well documented application. It means that it can provide comprehensive information to the developer willing to learn this application. Tomcat includes information concerning the installation guide, start up settings, platform support, and server configuration that are effortlessly available on the web.

Extra Level Of Security – In Apache Tomcat applications, you tend to acquire an additional level of security. Usually, corporates want to hide their data behind firewall protection. And they can seamlessly do so by installing this server application.

Stability – Apache Tomcat is one of the stable platforms on the web that runs any application efficiently. It has been considered an extremely stable version as it runs independently on Apache installation. Even if one of the features does not run on the application because of a certain error, the rest of the server will run effortlessly and without any interruption. This way, the application will live a wholesome life.

How to Setup Tomcat Clustering in Linux

Prerequisites

  • Two servers running Ubuntu 20.04 operating system.
  • A root user or a normal user with a sudo privileges.

Install Java JDK

Apache Tomcat is a Java based application. So you will need to install Java on both cluster nodes. You can run the following command to install Java:

				
					apt install default-jdk -y
				
			

After installing Java, verify the Java version using the following command:

				
					java -version
				
			

You should see the Java version in the following output:

				
					openjdk version "11.0.16" 2022-07-19
OpenJDK Runtime Environment (build 11.0.16+8-post-Ubuntu-0ubuntu120.04)
OpenJDK 64-Bit Server VM (build 11.0.16+8-post-Ubuntu-0ubuntu120.04, mixed mode, sharing)
				
			

Download Apache Tomcat

Next, you will need to download Apache Tomcat on both nodes. You can download it with the following command:

				
					wget https://dlcdn.apache.org/tomcat/tomcat-9/v9.0.65/bin/apache-tomcat-9.0.65.tar.gz
				
			

Once the download is complete, extract the downloaded file with the following command:

				
					tar -xvzf apache-tomcat-9.0.65.tar.gz
				
			

Next, move the extracted directory to the /opt directory:

				
					mv apache-tomcat-9.0.65 /opt/
				
			

Configure Tomcat for Remote Access

By default, Tomcat is accessible only from the local host. So you will need to configure both Tomcat instances for remote access. You can enable the remote access by editing the context.xml file.

To enable the Manager App for remote access, edit the following context.xml file:

				
					nano /opt/apache-tomcat-9.0.65/webapps/manager/META-INF/context.xml
				
			

Remove the following lines:

				
					  <Valve className="org.apache.catalina.valves.RemoteAddrValve"
         allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1" />
				
			

To enable the Host Manager App for remote access, edit the following context.xml file:

				
					nano /opt/apache-tomcat-9.0.65/webapps/host-manager/META-INF/context.xml
				
			

Remove the following lines:

				
					  <Valve className="org.apache.catalina.valves.RemoteAddrValve"
         allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1" />

				
			

Save and close the file when you finish.

Configure Apache Tomcat Clustering

At this point, Apache Tomcat is installed and configured on both nodes. Now, you will need to edit the Apache Tomcat configuration file on both nodes and set up clustering.

Open your command line editor and edit the Tomcat server.xml file:

				
					nano /opt/apache-tomcat-9.0.65/conf/server.xml
				
			

Find the following lines and change localhost to the IP address of each Tomcat Node.

				
					<Engine name="Catalina" defaultHost="localhost">
<Host name="localhost"  appBase="webapps

				
			

Next, add the following lines:

				
					<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"
                 channelSendOptions="6">

          <Manager className="org.apache.catalina.ha.session.BackupManager"
                   expireSessionsOnShutdown="false"
                   notifyListenersOnReplication="true"
                   mapSendOptions="6"/>
          <!--
          <Manager className="org.apache.catalina.ha.session.DeltaManager"
                   expireSessionsOnShutdown="false"
                   notifyListenersOnReplication="true"/>
          -->
          <Channel className="org.apache.catalina.tribes.group.GroupChannel">
            <Membership className="org.apache.catalina.tribes.membership.McastService"
                        address="228.0.0.4"
                        port="45564"
                        frequency="500"
                        dropTime="3000"/>
            <Receiver className="org.apache.catalina.tribes.transport.nio.NioReceiver"
                      address="auto"
                      port="5000"
                      selectorTimeout="100"
                      maxThreads="6"/>

            <Sender className="org.apache.catalina.tribes.transport.ReplicationTransmitter">
              <Transport className="org.apache.catalina.tribes.transport.nio.PooledParallelSender"/>
            </Sender>
            <Interceptor className="org.apache.catalina.tribes.group.interceptors.TcpFailureDetector"/>
            <Interceptor className="org.apache.catalina.tribes.group.interceptors.MessageDispatchInterceptor"/>
            <Interceptor className="org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor"/>
          </Channel>

          <Valve className="org.apache.catalina.ha.tcp.ReplicationValve"
                 filter=".*\.gif|.*\.js|.*\.jpeg|.*\.jpg|.*\.png|.*\.htm|.*\.html|.*\.css|.*\.txt"/>

          <Deployer className="org.apache.catalina.ha.deploy.FarmWarDeployer"
                    tempDir="/tmp/war-temp/"
                    deployDir="/tmp/war-deploy/"
                    watchDir="/tmp/war-listen/"
                    watchEnabled="false"/>

          <ClusterListener className="org.apache.catalina.ha.session.ClusterSessionListener"/>
        </Cluster>

				
			

Save and close the file when you are done.

Create a Systemd Service File for Tomcat

It is recommended to create systemd service file on both nodes to manage the Apache Tomcat service. You can create it with the following command:

				
					nano /etc/systemd/system/tomcat.service
				
			

Add the following configurations:

				
					[Unit]
Description=Apache Tomcat Server
After=syslog.target network.target

[Service]
Type=forking
User=root
Group=root

Environment=CATALINA_PID=/opt/apache-tomcat-9.0.65/temp/tomcat.pid
Environment=CATALINA_HOME=/opt/apache-tomcat-9.0.65
Environment=CATALINA_BASE=/opt/apache-tomcat-9.0.65

ExecStart=/opt/apache-tomcat-9.0.65/bin/catalina.sh start
ExecStop=/opt/apache-tomcat-9.0.65/bin/catalina.sh stop

RestartSec=10
Restart=always
[Install]
WantedBy=multi-user.target
				
			

Save the file when you are finish, then reload the systemd daemon with the following command:

				
					systemctl daemon-reload
				
			

Start Apache Tomcat Service

Now, start the Apache Tomcat service on both nodes using the following command:

				
					systemctl start tomcat
				
			

Then enable the Apache Tomcat service to start at system reboot using the following command:

				
					systemctl enable tomcat
				
			

You can now verify the status of the Apache Tomcat using the following command:

				
					systemctl status tomcat
				
			

You will get the following output:

				
					● tomcat.service - Apache Tomcat Server
   Loaded: loaded (/etc/systemd/system/tomcat.service; disabled; vendor preset: disabled)
   Active: active (running) since Tue 2022-08-13 09:26:42 EDT; 16s ago
  Process: 23184 ExecStart=/opt/tomcat/bin/catalina.sh start (code=exited, status=0/SUCCESS)
 Main PID: 23195 (java)
    Tasks: 34 (limit: 23694)
   Memory: 98.3M
   CGroup: /system.slice/tomcat.service
           └─23195 /usr/bin/java -Djava.util.logging.config.file=/opt/tomcat/conf/logging.properties -Djava.util.logging.manager=org.apache.j>

August 13 09:26:42 ubuntu systemd[1]: Starting Apache Tomcat Server...
August 13 09:26:42 ubuntu systemd[1]: Started Apache Tomcat Server.

				
			

Here please verify the Apache Tomcat listening ports using the following command:

				
					ss -antpl
				
			

You should see the Apache Tomcat listening ports in the following output:

				
					State      Recv-Q     Send-Q                   Local Address:Port         Peer Address:Port    Process                                        
LISTEN     0          4096                     127.0.0.53%lo:53                0.0.0.0:*        users:(("systemd-resolve",pid=299,fd=13))     
LISTEN     0          128                            0.0.0.0:22                0.0.0.0:*        users:(("sshd",pid=631,fd=3))                 
LISTEN     0          1                   [::ffff:127.0.0.1]:8005                    *:*        users:(("java",pid=4889,fd=59))               
LISTEN     0          100                                  *:8080                    *:*        users:(("java",pid=4889,fd=45))               
LISTEN     0          128                               [::]:22                   [::]:*        users:(("sshd",pid=631,fd=4))                 
LISTEN     0          50             [::ffff:208.117.85.180]:4000                    *:*        users:(("java",pid=4889,fd=50))     

				
			

If you want to check the Apache Tomcat logs, run the following command:

				
					tail -f /opt/apache-tomcat-9.0.65/logs/catalina.out
				
			

You can also stop the Apache Tomcat using the following command:

				
					systemctl stop tomcat
				
			

At this point, Apache Tomcat clustering is set up between both nodes.

Access Apache Tomcat

You can now access the Apache Tomcat instance using the URL http://your-server-ip:8080. You should see the Apache Tomcat dashboard on the following screen:

Now, click on the status button. You should see the Apache Tomcat cluster status:

Thank you for reading how to Setup Tomcat Clustering in Linux (Tutorial).

How to Setup Tomcat Clustering in Linux (Tutorial) Conclusion

In this Tomcat Clustering blog post, we explained Apache Tomcat, it’s installation process and then also showed you how to configure Tomcat clustering. You can now set up Apache Tomcat clustering in the production environment to achieve high availability. For more information about the how and why of clustered architecture, check out the Tomcat Clustering document.

Please take a look at our Apache Tomcat content here

Avatar for Hitesh Jethva
Hitesh Jethva

I am a fan of open source technology and have more than 10 years of experience working with Linux and Open Source technologies. I am one of the Linux technical writers for Cloud Infrastructure Services.

0 0 votes
Article Rating
Subscribe
Notify of
2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Satish Kumar

How Node1/Server1 and Node2/Server2 will communicate and where to check cluster status?

Satish Kumar

Do we need to deploy WAR files separately on both nodes?

2
0
Would love your thoughts, please comment.x
()
x