Hands-on: Setting Up Tomcat and Apache in CentOS (Self Implemented)

Step-1. Install CentOS 6 or letter (I have used CentOS 6)
Step-2. yum -y update (Solve: Another app is currently holding the yum lock; waiting for it to exit…)
Solution if you fail to stop the process :
#rm -f /var/run/yum.pid 2600
then update your yum
# yum -y update

yum clean all
rpm --rebuilddb

Make sure that yum-updatesd is started :
#/etc/init.d/yum-updatesd status
# /etc/init.d/yum-updatesd start
NB: This can be dangerous especially if you kill the wrong PID by mistake.

Code:
 # ps -ef | grep yum
root      3185  1207  0 14:47 pts/1    00:00:00 grep yum
root      3804     1  0 Jan11 ?        00:00:43 /usr/bin/python -tt /usr/sbin/yum-updatesd
# kill -9 3804
# ps -ef | grep yum
root      3197  1207  0 14:48 pts/1    00:00:00 grep yum
# yum update

Step-3. Step 1: Install JDK 1.8
You can download the latest JDK here: http://www.oracle.com/technetwork/java/javase/downloads/index.html this will download the jdk-8u20-linux-x64.tar.gz to the folder/ directory /home/IICT/Downloads/jdk-8u20-linux-x64.tar.gz . Now su root and copy the file to the /usr/java/

su root
mkdir /usr/java
cp /home/IICT/Downloads/jdk-8u20-linux-x64.tar.gz /usr/java/
cd /usr/java/
tar -xzf jdk-8u20-linux-x64.tar.gz
JAVA_HOME=/usr/java/jdk1.8.0_20
export JAVA_HOME
PATH=$JAVA_HOME/bin:$PATH
export PATH
echo $JAVA_HOME
Output: /usr/java/jdk1.8.0_20
Step-4. Setup tomcat 7
Download tomcat 7 or 8 in .tar.gz format (do not install using yum install tomcat from internet in .rpm format) from http://tomcat.apache.org/download-70.cgi . this will download the .tar.gz file in /home/IICT/Downloads directiry. copy them to /usr/share/

cp /home/IICT/Downloads/apache-tomcat-7.0.55.tar.gz /usr/share/
cd /usr/share/
tar -xzf apache-tomcat-7.0.55.tar.gz

cd /etc/init.d/
nano tomcat (script is)
#!/bin/bash
# description: Tomcat Start Stop Restart
# processname: tomcat
# chkconfig: 234 20 80
JAVA_HOME=/usr/java/jdk1.8.0_20
export JAVA_HOME
PATH=$JAVA_HOME/bin:$PATH
export PATH
CATALINA_HOME=/usr/share/apache-tomcat-7.0.55
case $1 in
start)
sh $CATALINA_HOME/bin/startup.sh
;;
stop)
sh $CATALINA_HOME/bin/shutdown.sh
;;
restart)
sh $CATALINA_HOME/bin/shutdown.sh
sh $CATALINA_HOME/bin/startup.sh
;;
esac
exit 0
(in cd /etc/init.d/)
chmod 755 tomcat
chkconfig –add tomcat
chkconfig –level 234 tomcat on
chkconfig –list tomcat
Output: tomcat 0:off 1:off 2:on 3:on 4:on 5:off 6:off
service tomcat start
service tomcat stop
service tomcat start
service tomcat restart
Output: Tomcat started.
[tomcat installation is ready… let set go]

Step-5: Install PHP:
yum install php
Total download size: 3.8 M
Installed size: 13 M
Is this ok [y/N]: y
Output: Complete!
Default Deployment folder/ directory for tomcat is  /usr/share/apache-tomcat-7.0.55/webapps/ROOT/  (.war deploy here)
and default Deployment folder of Apache is /var/www/html/

Advertisements

Install Tomcat 7 on CentOS, RHEL, or Fedora

http://www.davidghedini.com/pg/entry/install_tomcat_7_on_centos

Install Tomcat 7 on CentOS, RHEL, or Fedora

This post will cover installing and basic configuration of Tomcat 7 on CentOS 5.x. or CentOS 6.x

Tomcat 7 implements the JavaServer Pages 2.2 and Servlet 3.0 specifications and a number of new features. The Manager application also has a new look and finer-grain roles and access than 6.x

In this post, we’ll install Tomcat 7, the new JDK 7, configure Tomcat as a service, create a start/stop script, and (optionally) configure Tomcat to run under a non-root user.

We will also configure basic access to Tomcat Manager and take a quick look at memory management using JAVA_OPTS

Finally, we will look at running Tomcat on port 80 as well as some strategies for running Tomcat behind Apache.

I have just updated this post with Tomcat 7.0.29, the current stable release of Tomcat 7.

If you are using a different release, simply change the file names below accordingly.

To begin, we’ll need to install the Java Development Kit (JDK) 7

JDK 1.6 is the minimum JDK version for Tomcat 7.

Step 1: Install JDK 1.7

You can download the latest JDK here: http://www.oracle.com/technetwork/java/javase/downloads/index.html

We’ll install the latest JDK, which is JDK 7, Update 5. The JDK is specific to 32 and 64 bit versions.

My CentOS box is 64 bit, so I’ll need: jdk-7u5-linux-x64.tar.gz.

If you are on 32 bit, you’ll need: jdk-7u5-linux-i586.tar.gz

Start by creating a new directory /usr/java:

  1. [root@srv6 ~]# mkdir /usr/java

Change to the /usr/java directory we created

  1. [root@srv6 ~]# cd /usr/java
  2. [root@srv6 java ]#

Download the appropriate JDK and save it to /usr/java directory we created above.

Unpack jdk-7u5-linux-x64.tar.gz in the /usr/java directory using tar -xzf:

  1. [root@srv6 java]# tar -xzf jdk-7u5-linux-x64.tar.gz

This will create the directory /usr/java/jdk1.7.0_05. This will be our JAVA_HOME.

We can now set JAVA_HOME and put Java into the path of our users.

To set it for your current session, you can issue the following from the CLI:

  1. [root@srv6 java]# JAVA_HOME=/usr/java/jdk1.7.0_05
  2. [root@srv6 java]# export JAVA_HOME
  3. [root@srv6 java]# PATH=$JAVA_HOME/bin:$PATH
  4. [root@srv6 java]# export PATH

To set the JAVA_HOME permanently, however, we need to add below to the ~/.bash_profile of the user (in this case, root).
We can also add it /etc/profile and then source it to give to all users.

  1. JAVA_HOME=/usr/java/jdk1.7.0_05
  2. export JAVA_HOME
  3. PATH=$JAVA_HOME/bin:$PATH
  4. export PATH

Once you have added the above to ~/.bash_profile, you should log out, then log back in and check that the JAVA_HOME is set correctly.

  1. [root@srv6 ~]#  echo $JAVA_HOME
  2. /usr/java/jdk1.7.0_05

Note: If you decided to use JDK 6 rather than 7 as we did above, simply save the JDK 6 bin file to /opt (or another location), then navigate to /usr/java and issue: ‘sh /opt/jdk-6u33-linux-x64.bin’. This will create a JAVA Home of /usr/java/jdk1.6.0.33

Step 2: Download and Unpack Tomcat 7.0.29 (or latest)

We will install Tomcat 7 under /usr/share.

Switch to the /usr/share directory:

  1. [root@srv6 ~]# cd /usr/share
  2. [root@srv6 share ]#

Download apache-tomcat-7.0.29.tar.gz (or the latest version) here

and save it to /usr/share

Once downloaded, you should verify the MD5 Checksum for your Tomcat download using the md5sum command.

  1. [root@srv6 share ]# md5sum apache-tomcat-7.0.29.tar.gz
  2. 307076fa3827e19fa9b03f3ef7cf1f3f *apache-tomcat-7.0.29.tar.gz

Compare the output above to the MD5 Checksum provided next to the download link and you used above and check that it matches.

unpack the file using tar -xzf:

  1. [root@srv6 share ]# tar -xzf apache-tomcat-7.0.29.tar.gz

This will create the directory /usr/share/apache-tomcat-7.0.29

Step 3: Configure Tomcat to Run as a Service.

We will now see how to run Tomcat as a service and create a simple Start/Stop/Restart script, as well as to start Tomcat at boot.

Change to the /etc/init.d directory and create a script called ‘tomcat’ as shown below.

  1. [root@srv6 share]# cd /etc/init.d
  2. [root@srv6 init.d]# vi tomcat

And here is the script we will use.

  1. #!/bin/bash
  2. # description: Tomcat Start Stop Restart
  3. # processname: tomcat
  4. # chkconfig: 234 20 80
  5. JAVA_HOME=/usr/java/jdk1.7.0_05
  6. export JAVA_HOME
  7. PATH=$JAVA_HOME/bin:$PATH
  8. export PATH
  9. CATALINA_HOME=/usr/share/apache-tomcat-7.0.29
  10. case $1 in
  11. start)
  12. sh $CATALINA_HOME/bin/startup.sh
  13. ;;
  14. stop)
  15. sh $CATALINA_HOME/bin/shutdown.sh
  16. ;;
  17. restart)
  18. sh $CATALINA_HOME/bin/shutdown.sh
  19. sh $CATALINA_HOME/bin/startup.sh
  20. ;;
  21. esac
  22. exit 0

The above script is simple and contains all of the basic elements you will need to get going.

As you can see, we are simply calling the startup.sh and shutdown.sh scripts located in the Tomcat bin directory (/usr/share/apache-tomcat-7.0.29/bin).

You can adjust your script according to your needs and, in subsequent posts, we’ll look at additional examples.

CATALINA_HOME is the Tomcat home directory (/usr/share/apache-tomcat-7.0.29)

Now, set the permissions for your script to make it executable:

  1. [root@srv6 init.d]# chmod 755 tomcat

We now use the chkconfig utility to have Tomcat start at boot time. In my script above, I am using chkconfig: 234 20 80. 2345 are the run levels and 20 and 80 are the stop and start priorities respectively. You can adjust as needed.

  1. [root@srv6 init.d]# chkconfig –add tomcat
  2. [root@srv6 init.d]# chkconfig –level 234 tomcat on

Verify it:

  1. [root@srv6 init.d]# chkconfig –list tomcat
  2. tomcat          0:off   1:off   2:on    3:on    4:on    5:off   6:off

Now, let’s test our script.

Start Tomcat:

  1. [root@srv6 ~]# service tomcat start
  2. Using CATALINA_BASE:   /usr/share/apache-tomcat-7.0.29
  3. Using CATALINA_HOME:   /usr/share/apache-tomcat-7.0.29
  4. Using CATALINA_TMPDIR: /usr/share/apache-tomcat-7.0.29/temp
  5. Using JRE_HOME:        /usr/java/jdk1.7.0_05
  6. Using CLASSPATH:       /usr/share/apache-tomcat-7.0.29/bin/bootstrap.jar:/usr/share/apache-tomcat-7.0.29/bin/tomcat-juli.jar

Stop Tomcat:

  1. [root@srv6 ~]# service tomcat stop
  2. Using CATALINA_BASE:   /usr/share/apache-tomcat-7.0.29
  3. Using CATALINA_HOME:   /usr/share/apache-tomcat-7.0.29
  4. Using CATALINA_TMPDIR: /usr/share/apache-tomcat-7.0.29/temp
  5. Using JRE_HOME:        /usr/java/jdk1.7.0_05
  6. Using CLASSPATH:       /usr/share/apache-tomcat-7.0.29/bin/bootstrap.jar:/usr/share/apache-tomcat-7.0.29/bin/tomcat-juli.jar

Restarting Tomcat (Must be started first):

  1. [root@srv6 ~]# service tomcat restart
  2. Using CATALINA_BASE:   /usr/share/apache-tomcat-7.0.29
  3. Using CATALINA_HOME:   /usr/share/apache-tomcat-7.0.29
  4. Using CATALINA_TMPDIR: /usr/share/apache-tomcat-7.0.29/temp
  5. Using JRE_HOME:        /usr/java/jdk1.7.0_05
  6. Using CLASSPATH:       /usr/share/apache-tomcat-7.0.29/bin/bootstrap.jar:/usr/share/apache-tomcat-7.0.29/bin/tomcat-juli.jar
  7. Using CATALINA_BASE:   /usr/share/apache-tomcat-7.0.29
  8. Using CATALINA_HOME:   /usr/share/apache-tomcat-7.0.29
  9. Using CATALINA_TMPDIR: /usr/share/apache-tomcat-7.0.29/temp
  10. Using JRE_HOME:        /usr/java/jdk1.7.0_05
  11. Using CLASSPATH:       /usr/share/apache-tomcat-7.0.29/bin/bootstrap.jar:/usr/share/apache-tomcat-7.0.29/bin/tomcat-juli.jar

We should review the Catalina.out log located at /usr/share/apache-tomcat-7.0.29/logs/catalina.out and check for any errors.

  1. [root@srv6 init.d]# more /usr/share/apache-tomcat-7.0.29/logs/catalina.out

We can now access the Tomcat Manager page at:

http://yourdomain.com:8080 or http://yourIPaddress:8080 and we should see the Tomcat home page.

 

Step 4: Configuring Tomcat Manager Access.

Tomcat 7 contains a number of changes that offer finer-grain roles.

For security reasons, no users or passwords are created for the Tomcat manager roles by default. In a production deployment, it is always best to remove the Manager application.

To set roles, user name(s) and password(s), we need to configure the tomcat-users.xml file located at $CATALINA_HOME/conf/tomcat-users.xml.

In the case of our installation, $CATALINA_HOME is located at /usr/share/apache-tomcat-7.0.29.

By default the Tomcat 7 tomcat-users.xml file will have the elements between the and tags commented-out. .

New roles for Tomcat 7 offer finer-grained access and The following roles are now available:

manager-gui
manager-status
manager-jmx
manager-script
admin-gu
admin-script.

We can set the manager-gui role, for example as below

:

  1. <tomcat-users>
  2. <role rolename=“manager-gui”/>
  3. <user username=“tomcat” password=“secret” roles=“manager-gui”/>
  4. </tomcat-users>

Caution should be exercised in granting multiple roles so as not to under-mind security.

Step 5 (Oprtional): Manage Memory Usage Using JAVA_OPTS.

Getting the right heap memory settings for your installation will depend on a number of factors.

For simplicity, we will set our inital heap size, Xms, and our maximum heap size, Xmx, to the same value of 128 Mb

Simliarly, there are several approaches you can take as to where and how you set your JAVA_OPTS

Again, for simplicity, we will add our JAVA_OPTS memory parameters in our Catalina.sh file.

So, open the Catalina.sh file located under /usr/share/apache-tomcat-7.0.29/bin with a text editor or vi.

Since we are using 128 Mb for both initial and maximum heap size, add the following line to Catalina.sh

  1. JAVA_OPTS=“-Xms128m -Xmx128m”

I usually just add this in the second line of the file so it looks as so:

  1. #!/bin/sh
  2. JAVA_OPTS=“-Xms128m -Xmx128m”
  3. # Licensed to the Apache Software Foundation (ASF) under one or more
  4. # contributor license agreements.  See the NOTICE file distributed with
  5. # this work for additional information regarding copyright ownership.
  6. # The ASF licenses this file to You under the Apache License, Version 2.0
  7. # (the “License”); you may not use this file except in compliance with
  8. # the License.  You may obtain a copy of the License at

 

Step 6 (Optional): How to Run Tomcat using Minimally Privileged (non-root) User.

In our Tomcat configuration above, we are running Tomcat as Root.

For security reasons, it is always best to run services with the only those privileges that are necessary.

There are some who make a strong case that this is not required, but it’s always best to err on the side of caution.

To run Tomcat as non-root user, we need to do the following:

1. Create the group ‘tomcat’:

  1. [root@srv6 ~]# groupadd tomcat

2. Create the user ‘tomcat’ and add this user to the tomcat group we created above.

  1. [root@srv6 ~]# useradd -s /bin/bash -g tomcat tomcat

The above will create a home directory for the user tomcat in the default user home as /home/tomcat

If we want the home directory to be elsewhere, we simply specify so using the -d switch.

  1. [root@srv6 ~]# useradd -g tomcat -d /usr/share/apache-tomcat-7.0.29/tomcat tomcat

The above will create the user tomcat’s home directory as /usr/share/apache-tomcat-7.0.29/tomcat

3. Change ownership of the tomcat files to the user tomcat we created above:

  1. [root@srv6 ~]# chown -Rf tomcat.tomcat /usr/share/apache-tomcat-7.0.29/

Note: it is possible to enhance our security still further by making certain files and directories read-only. This will not be covered in this post and care should be used when setting such permissions.

4. Adjust the start/stop service script we created above. In our new script, we need to su to the user tomcat:

  1. #!/bin/bash
  2. # description: Tomcat Start Stop Restart
  3. # processname: tomcat
  4. # chkconfig: 234 20 80
  5. JAVA_HOME=/usr/java/jdk1.7.0_05
  6. export JAVA_HOME
  7. PATH=$JAVA_HOME/bin:$PATH
  8. export PATH
  9. CATALINA_HOME=/usr/share/apache-tomcat-7.0.29/bin
  10. case $1 in
  11. start)
  12. /bin/su tomcat $CATALINA_HOME/startup.sh
  13. ;;
  14. stop)
  15. /bin/su tomcat $CATALINA_HOME/shutdown.sh
  16. ;;
  17. restart)
  18. /bin/su tomcat $CATALINA_HOME/shutdown.sh
  19. /bin/su tomcat $CATALINA_HOME/startup.sh
  20. ;;
  21. esac
  22. exit 0

 

Step 7 (Optional): How to Run Tomcat on Port 80 as Non-Root User.

Note: the following applies when you are running Tomcat in “stand alone” mode with Tomcat running under the minimally privileged user Tomcat we created in the previous step.

To run services below port 1024 as a user other than root, you can add the following to your IP tables:

  1. [root@srv6 ~]# iptables -t nat -A PREROUTING -p tcp -m tcp –dport 80 -j REDIRECT –to-ports 8080
  2. [root@srv6 ~]# iptables -t nat -A PREROUTING -p udp -m udp –dport 80 -j REDIRECT –to-ports 8080

Be sure to save and restart your IP Tables.

Step 8 (Optional): Running Tomcat behind Apache

As an alternative to running Tomcat on port 80, if you have Apache in front of Tomcat, you can use mod_proxy as well as ajp connector to map your domain to your Tomcat application(s) using an Apache vhost as shown below.

While Tomcat has improved it’s ‘standalone performance’, I still prefer to have Apace in front of it for a number of reasons.

In your Apache config, be sure to set KeepAlive to ‘on’. Apache tuning, of course, is a whole subject in itself…

Example 1: VHOST with mod_proxy:

  1. <VirtualHost *:80>
  2.     ServerAdmin admin@yourdomain.com
  3.     ServerName yourdomain.com
  4.     ServerAlias www.yourdomain.com
  5.     ProxyRequests Off
  6.     ProxyPreserveHost On
  7.     <Proxy *>
  8.        Order allow,deny
  9.        Allow from all
  10.     </Proxy>
  11.     ProxyPass / http://localhost:8080/
  12.     ProxyPassReverse / http://localhost:8080/
  13.     ErrorLog logs/yourdomain.com-error_log
  14.     CustomLog logs/yourdomain.com-access_log common
  15. </VirtualHost>

Example 2: VHOST with ajp connector and mod_proxy:

  1. <VirtualHost *:80>
  2.     ServerAdmin admin@yourdomain.com
  3.     ServerName yourdomain.com
  4.     ServerAlias www.yourdomain.com
  5.     ProxyRequests Off
  6.     ProxyPreserveHost On
  7.     <Proxy *>
  8.     Order allow,deny
  9.     Allow from all
  10.     </Proxy>
  11.     ProxyPass / ajp://localhost:8009/
  12.     ProxyPassReverse / ajp://localhost:8009/
  13.     ErrorLog logs/yourdomain.com-error_log
  14.     CustomLog logs/yourdomain.com-access_log common
  15. </VirtualHost>

In both vhost examples above, we are “mapping” the domain to Tomcat’s ROOT directory.

If we wish to map to an application such as yourdomain.com/myapp, we can add some rewrite as shown below.

This will rewrite all requests for yourdomain.com to yourdomain.com/myapp.

Example 3: VHOST with rewrite:

  1. <VirtualHost *:80>
  2.     ServerAdmin admin@yourdomain.com
  3.     ServerName yourdomain.com
  4.     ServerAlias www.yourdomain.com
  5.     RewriteEngine On
  6.     RewriteRule ^/$ myapp/ [R=301]
  7.     ProxyRequests Off
  8.     ProxyPreserveHost On
  9.     <Proxy *>
  10.     Order allow,deny
  11.     Allow from all
  12.     </Proxy>
  13.     ProxyPass / ajp://localhost:8009/
  14.     ProxyPassReverse / ajp://localhost:8009/
  15.     ErrorLog logs/yourdomain.com-error_log
  16.     CustomLog logs/yourdomain.com-access_log common
  17. </VirtualHost>

Related Tomcat Posts

Learn More About Apache Tomcat 7 Apache Tomcat Foundation Tomcat 7

Install Tomcat 7 on CentOS / RHEL

PLEASE NOTE: This post covers installation of Tomcat 7 along with JDK 6. For installation of Tomcat 7 with JDK 6 or JDK 7, please see my updated and expanded post here:

 

This post will cover installing and basic configuration of Tomcat 7 on CentOS 5.x.

The procedure can be used for Fedora and RHEL as well.

Tomcat 7 implements the JavaServer Pages 2.2 and Servlet 3.0 specifications and a number of new features. The Manager application also has a new look with finer-grain roles and access than 6.x

In this post, we’ll install the required JDK, Tomcat, configure Tomcat as a service, create a start/stop/restart script, and (optionally) configure Tomcat to run under a non-root user.

For this installation, we’ll use Tomcat 7.0.19, the current stable release of Tomcat 7. This post began with the first Tomcat 7 release and I have tried to keep it updated to keep things as “copy and paste” as possible.

I’ve also updated the post for JDK 6, Update 26.

To begin, we’ll need to install the Java Development Kit (JDK) 1.6

JDK 1.6 is the minimum JDK version for Tomcat 7.

If you do have the JDK installed, you can skip to: Step 2: Download and Unpack Tomcat 7.0.19:

Step 1: Install JDK 1.6

You can download the JDK here: http://www.oracle.com/technetwork/java/javase/downloads/index.html

We’ll install the latest JDK, which is JDK 6 Update 26. The JDK is specific to 32 and 64 bit versions.

My CentOS box is 64 bit, so I’ll need: jdk-6u26-linux-x64.bin

If you are on 32 bit, you’ll need: jdk-6u26-linux-i586.bin

Download the appropriate JDK and save it to a directory. I’m saving it to /root.

Move (mv) or copy (cp) the file to the /opt directory:

  1. [root@srv6 ~]# mv jdk-6u26-linux-x64.bin /opt/jdk-6u26-linux-x64.bin

Create a new directory /usr/java.

  1. [root@srv6 ~]# mkdir /usr/java

Change to the /usr/java directory we created and install the JDK using ‘sh /opt/jdk-6u26-linux-x64.bin’

  1. [root@srv6 ~]# cd /usr/java
  2. [root@srv6 java]# sh /opt/jdk-6u26-linux-x64.bin

Set the JAVA_HOME path. This is where we installed our JDK above.

To set it for your current session, you can issue the following from the CLI:

  1. [root@srv6 java]# JAVA_HOME=/usr/java/jdk1.6.0_26
  2. [root@srv6 java]# export JAVA_HOME
  3. [root@srv6 java]# PATH=$JAVA_HOME/bin:$PATH
  4. [root@srv6 java]# export PATH

To set the JAVA_HOME permanently, we add below to either the ~/.bashrc or ~/.bash_profile of the user (in this case, root).

We can also add it /etc/profile and then source it to give to all users.

  1. JAVA_HOME=/usr/java/jdk1.6.0_26
  2. export JAVA_HOME
  3. PATH=$JAVA_HOME/bin:$PATH
  4. export PATH

Once you have added the above to ~/.bash_profile or ~/.bashrc, you should log out, then log back in and check that the JAVA_HOME is set correctly.

  1. [root@srv6 ~]#  echo $JAVA_HOME
  2. /usr/java/jdk1.6.0_26

 

Step 2: Download and Unpack Tomcat 7.0.19

Download apache-tomcat-7.0.19.tar.gz here

Alternatively, you can download using wget.

  1. [root@srv6 ~]#  wget http://apache.mivzakim.net/tomcat/tomcat-7/v7.0.19/bin/apache-tomcat-7.0.19.tar.gz

Save the file to a directory. I’m saving it to /root/apache-tomcat-7.0.19.tar.gz

Before proceeding, you should verify the MD5 Checksum for your Tomcat download (or any other download).

Since we saved the Tomcat download to /root/apache-tomcat-7.0.19.tar.gz, we’ll go to the /root directory and use the md5sum command.

  1. [root@srv6 ~]# md5sum apache-tomcat-7.0.19.tar.gz
  2. 5a5e9bc742714d1b7210d9f68764fd8e *apache-tomcat-7.0.19.zip

Compare the output above to the MD5 Checksum provided by here the Apache Tomcat MD5 page and insure that they match exactly.

Now, move (mv) or copy (cp) the file to the /usr/share directory:

  1. [root@srv6 ~]# mv apache-tomcat-7.0.19.tar.gz /usr/share/apache-tomcat-7.0.19.tar.gz

Change to the /usr/share directory and unpack the file using tar -xzf:

  1. [root@srv6 ~]# cd /usr/share
  2. [root@sv2 srv6 ]# tar -xzf apache-tomcat-7.0.19.tar.gz

This will create the directory /usr/share/apache-tomcat-7.0.19

Step 3: Configure Tomcat to Run as a Service.

We will now see how to run Tomcat as a service and create a simple Start/Stop/Restart script, as well as to start Tomcat at boot.

Change to the /etc/init.d directory and create a script called ‘tomcat’ as shown below.

  1. [root@srv6 share]# cd /etc/init.d
  2. [root@srv6 init.d]# vi tomcat

 

  1. #!/bin/bash
  2. # description: Tomcat Start Stop Restart
  3. # processname: tomcat
  4. # chkconfig: 234 20 80
  5. JAVA_HOME=/usr/java/jdk1.6.0_26
  6. export JAVA_HOME
  7. PATH=$JAVA_HOME/bin:$PATH
  8. export PATH
  9. CATALINA_HOME=/usr/share/apache-tomcat-7.0.19
  10. case $1 in
  11. start)
  12. sh $CATALINA_HOME/bin/startup.sh
  13. ;;
  14. stop)
  15. sh $CATALINA_HOME/bin/shutdown.sh
  16. ;;
  17. restart)
  18. sh $CATALINA_HOME/bin/shutdown.sh
  19. sh $CATALINA_HOME/bin/startup.sh
  20. ;;
  21. esac
  22. exit 0

The above script is simple and contains all of the basic elements you will need to get going.

As you can see, we are simply calling the startup.sh and shutdown.sh scripts located in the Tomcat bin directory (/usr/share/apache-tomcat-7.0.19/bin).

You can adjust your script according to your needs and, in subsequent posts, we’ll look at additional examples.

CATALINA_HOME is the Tomcat home directory (/usr/share/apache-tomcat-7.0.19)

Now, set the permissions for your script to make it executable:

  1. [root@srv6 init.d]# chmod 755 tomcat

We now use the chkconfig utility to have Tomcat start at boot time. In my script above, I am using chkconfig: 234 20 80. 2445 are the run levels and 20 and 80 are the stop and start priorities respectively. You can adjust as needed.

  1. [root@srv6 init.d]# chkconfig –add tomcat
  2. [root@srv6 init.d]# chkconfig –level 234 tomcat on

Verify it:

  1. [root@srv6 init.d]# chkconfig –list tomcat
  2. tomcat          0:off   1:off   2:on    3:on    4:on    5:off   6:off

Now, let’s test our script.

Start Tomcat:

  1. [root@srv6 ~]# service tomcat start
  2. Using CATALINA_BASE:   /usr/share/apache-tomcat-7.0.19
  3. Using CATALINA_HOME:   /usr/share/apache-tomcat-7.0.19
  4. Using CATALINA_TMPDIR: /usr/share/apache-tomcat-7.0.19/temp
  5. Using JRE_HOME:        /usr/java/jdk1.6.0_26
  6. Using CLASSPATH:       /usr/share/apache-tomcat-7.0.19/bin/bootstrap.jar:/usr/share/apache-tomcat-7.0.19/bin/tomcat-juli.jar

Stop Tomcat:

  1. [root@srv6 ~]# service tomcat stop
  2. Using CATALINA_BASE:   /usr/share/apache-tomcat-7.0.19
  3. Using CATALINA_HOME:   /usr/share/apache-tomcat-7.0.19
  4. Using CATALINA_TMPDIR: /usr/share/apache-tomcat-7.0.19/temp
  5. Using JRE_HOME:        /usr/java/jdk1.6.0_26
  6. Using CLASSPATH:       /usr/share/apache-tomcat-7.0.19/bin/bootstrap.jar:/usr/share/apache-tomcat-7.0.19/bin/tomcat-juli.jar

Restarting Tomcat (Must be started first):

  1. [root@srv6 ~]# service tomcat restart
  2. Using CATALINA_BASE:   /usr/share/apache-tomcat-7.0.19
  3. Using CATALINA_HOME:   /usr/share/apache-tomcat-7.0.19
  4. Using CATALINA_TMPDIR: /usr/share/apache-tomcat-7.0.19/temp
  5. Using JRE_HOME:        /usr/java/jdk1.6.0_26
  6. Using CLASSPATH:       /usr/share/apache-tomcat-7.0.19/bin/bootstrap.jar:/usr/share/apache-tomcat-7.0.19/bin/tomcat-juli.jar
  7. Using CATALINA_BASE:   /usr/share/apache-tomcat-7.0.19
  8. Using CATALINA_HOME:   /usr/share/apache-tomcat-7.0.19
  9. Using CATALINA_TMPDIR: /usr/share/apache-tomcat-7.0.19/temp
  10. Using JRE_HOME:        /usr/java/jdk1.6.0_26
  11. Using CLASSPATH:       /usr/share/apache-tomcat-7.0.19/bin/bootstrap.jar:/usr/share/apache-tomcat-7.0.19/bin/tomcat-juli.jar

We should review the Catalina.out log located at /usr/share/apache-tomcat-7.0.19/logs/catalina.out and check for any errors.

  1. [root@srv6 init.d]# more /usr/share/apache-tomcat-7.0.19/logs/catalina.out

We can now access the swanky new Tomcat Manager page at:

http://yourdomain.com:8080 or http://yourIPaddress:8080 and we should see the Tomcat home page.

 

Step 4: Configuring Tomcat Manager Access.

Tomcat 7 contains a number of changes that offer finer-grain roles.

For security reasons, no users or passwords are created for the Tomcat manager roles by default. In a production deployment, it is always best to remove the Manager application.

To set roles, user name(s) and password(s), we need to configure the tomcat-users.xml file located at $CATALINA_HOME/conf/tomcat-users.xml.

In the case of our installation, $CATALINA_HOME is located at /usr/share/apache-tomcat-7.0.19.

By default the Tomcat 7 tomcat-users.xml file will look as below.

  1. <!–
  2.   Licensed to the Apache Software Foundation (ASF) under one or more
  3.   contributor license agreements.  See the NOTICE file distributed with
  4.   this work for additional information regarding copyright ownership.
  5.   The ASF licenses this file to You under the Apache License, Version 2.0
  6.   (the “License”); you may not use this file except in compliance with
  7.   the License.  You may obtain a copy of the License at
  8.       http://www.apache.org/licenses/LICENSE-2.0
  9.   Unless required by applicable law or agreed to in writing, software
  10.   distributed under the License is distributed on an “AS IS” BASIS,
  11.   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12.   See the License for the specific language governing permissions and
  13.   limitations under the License.
  14. –>
  15. <tomcat-users>
  16. <!–
  17.   NOTE:  By default, no user is included in the “manager-gui” role required
  18.   to operate the “/manager/html” web application.  If you wish to use this app,
  19.   you must define such a user – the username and password are arbitrary.
  20. –>
  21. <!–
  22.   NOTE:  The sample user and role entries below are wrapped in a comment
  23.   and thus are ignored when reading this file. Do not forget to remove
  24.   <!.. ..> that surrounds them.
  25. –>
  26. <!–
  27.   <role rolename=“tomcat”/>
  28.   <role rolename=“role1”/>
  29.   <user username=“tomcat” password=“tomcat” roles=“tomcat”/>
  30.   <user username=“both” password=“tomcat” roles=“tomcat,role1”/>
  31.   <user username=“role1” password=“tomcat” roles=“role1”/>
  32. –>
  33. </tomcat-users>

Note that while examples are provided, the elements between the <tomcat-users> and </tomcat-users> tags have been commented-out.

New roles for Tomcat 7 offer finer-grained access.

The following roles are available:

manager-gui
manager-status
manager-jmx
manager-script
admin-gu
admin-script.

We can enable access for the manager-gui role, for example as below:

  1. <tomcat-users>
  2. <role rolename=“manager-gui”>
  3. <user username=“tomcat” password=“secret” roles=“manager-gui”>
  4. </user>
  5. </role></tomcat-users>

Caution should be exercised in granting multiple roles so as not to under-mind security.

Step 5 (Optional): How to Run Tomcat using Minimally Privileged (non-root) User.

In our Tomcat configuration above, we are running Tomcat as Root.

For security reasons, it is always best to run services with the only those privileges that are necessary.

There are some who make a strong case that this is not required, but it’s always best to err on the side of caution.

To run Tomcat as non-root user, we need to do the following:

1. Create the group ‘tomcat’:

  1. [root@srv6 ~]# groupadd tomcat

2. Create the user ‘tomcat’ and add this user to the tomcat group we created above.

  1. [root@srv6 ~]# useradd -s /bin/bash -g tomcat tomcat

The above will create a home directory for the user tomcat in the default user home as /home/tomcat

If we want the home directory to be elsewhere, we simply specify so using the -d switch.

  1. [root@srv6 ~]# useradd -g tomcat -d /usr/share/apache-tomcat-7.0.19/tomcat tomcat

The above will create the user tomcat’s home directory as /usr/share/apache-tomcat-7.0.19/tomcat

3. Change ownership of the tomcat files to the user tomcat we created above:

  1. [root@srv6 ~]# chown -Rf tomcat.tomcat /usr/share/apache-tomcat-7.0.19/

Note: it is possible to enhance our security still further by making certain files and directories read-only. This will not be covered in this post and care should be used when setting such permissions.

4. Adjust the start/stop service script we created above. In our new script, we need to su to the user tomcat:

  1. #!/bin/bash
  2. # description: Tomcat Start Stop Restart
  3. # processname: tomcat
  4. # chkconfig: 234 20 80
  5. JAVA_HOME=/usr/java/jdk1.6.0_26
  6. export JAVA_HOME
  7. PATH=$JAVA_HOME/bin:$PATH
  8. export PATH
  9. TOMCAT_HOME=/usr/share/apache-tomcat-7.0.19/bin
  10. case $1 in
  11. start)
  12. /bin/su tomcat $TOMCAT_HOME/startup.sh
  13. ;;
  14. stop)
  15. /bin/su tomcat $TOMCAT_HOME/shutdown.sh
  16. ;;
  17. restart)
  18. /bin/su tomcat $TOMCAT_HOME/shutdown.sh
  19. /bin/su tomcat $TOMCAT_HOME/startup.sh
  20. ;;
  21. esac
  22. exit 0

 

Step 6 (Optional): How to Run Tomcat on Port 80 as Non-Root User.

Note: the following applies when you are running Tomcat in “stand alone” mode with Tomcat running under the minimally privileged user Tomcat we created in the previous step.

To run services below port 1024 as a user other than root, you can add the following to your IP tables:

  1. [root@srv6 ~]# iptables -t nat -A PREROUTING -p tcp -m tcp –dport 80 -j REDIRECT –to-ports 8080
  2. [root@srv6 ~]# iptables -t nat -A PREROUTING -p udp -m udp –dport 80 -j REDIRECT –to-ports 8080

Be sure to save and restart your iptables for the above change to take affect.

Tomcat Clustering – A Step By Step Guide

Apache Tomcat is a great performer on its own, but if you’re expecting more traffic as your site expands, or are thinking about the best way to provide high availability, you’ll be happy to know that Tomcat also shines in a clustered environment. With built-in support for both synchronous and asynchronous in-memory and external session replication, cluster segmentation, and compatibility with all common load balancing solutions, your Tomcat servers are ready for the cluster right out of the box.

In this article, we’ll show you how easy it is to set up a simple Tomcat cluster with load balancing and session replication.

This simple step-by-step guide will walk you through every step of the process in plain English, from installing the load balancer, to configuring mod_jk, to enabling Tomcat’s built-in session replication capabilities. Along the way, we’ll point out common problem areas, to help you avoid configuration mistakes before they happen.

A Simple Explanation of Clustering

Although clustering can seem like a complicated topic, the premise is quite simple. A clustered architecture is used to solve one or more of the following problems:

  • A single server cannot handle the high number of incoming requests efficiently
  • A stateful application needs a way of preserving session data if its server fails
  • A developer requires the capability to make configuration changes or deploy updates to their applications without discontinuing service.

A clustered architecture solves these problems using a combination of load balancing, multiple server “workers” to process the balanced load, and some kind of session replication. Depending on the needs of the application, only some of these components may be used, or additional components such as caching and compression engines.

Since this is a how-to guide, we’ll stop the general information session here, and move on to setting up a working Tomcat cluster. However, if you’re new to clustering, it’s probably a good idea to do a little more reading up on the subject.

For more information about the how and why of clustered architecture, check out our Tomcat Clustering Basics article for an in-depth look at all the components of a cluster, comparisons of different approaches, and more.

About Our Example Set-Up

For the purposes of this tutorial, we’ll use a simple clustered configuration:

  • Apache HTTPD with mod_jk (for load balancing)
  • 2 Tomcat 6.x instances
  • in-memory session replication (via Tomcat’s built in functionality)

This configuration was chosen because it is a simple example of a very common clustering configuration used by many Tomcat users. Additionally, Apache HTTPD with mod_jk or mod_proxy is currently the default clustering solution recommended in the official Tomcat documentation provided by Apache.

We demonstrate configuration with mod_jk rather than mod_proxy for two reasons: it’s a little more complex, and requires some additional steps, and it’s currently the more mature load balancing connector, with a wider user base in the Tomcat community. Additionally, while new releases of mod_proxy are tied to Apache HTTPD releases, mod_jk is developed and released separately from Tomcat, so its features tend to be more current.

Using this tutorial as a basic reference, you should be able to find enough information elsewhere to create more customized or complex configurations. If you are curious about these kinds of situations, or want to know more about how other common approaches to Tomcat clustering stack up against one another, check out our Tomcat Cluster basics article for an in-depth guide.

Setting Up Your Tomcat Cluster

Let’s get started!

Step 1 – Install Tomcat instances and Apache HTTPD

If you haven’t already installed them, the first thing to do is to download and install the latest stable versions of Apache Tomcat 6.x and Apache HTTPD. You can find the latest stable versions on the Apache HTTPD and Tomcat project sites.

Depending on how you want to set up your servers for the purposes of this tutorial, you can either install these elements on multiple servers or a single server; the only differences will be in the port and address configuration steps. Simply follow standard conventions for sharing a single machine with multiple network services (don’t overlap ports, don’t use conflicting names, and so on). If you only want to use this tutorial to test different clustering configurations, the multiple Tomcat instances can live on the same machine, and even share the same base directory, using the CATALINA_BASE variable, as long as you remember that you should move to a set-up that reflects your actual production environment before doing any benchmark testing.

For the purposes of this tutorial, we’ll assume that you understand how to install these components. If you need additional help, don’t worry – the Apache HTTPD installation documentation is quite good, and we’ve created a simple guide to installing Tomcat 6 on multiple platforms, which you can find here.

Step 2 – Download and install mod_jk

mod_jk is the Apache HTTPD module that will be used to provide our cluster with its load balancing and proxy capabilities. It uses the AJP protocol to facilitate fast communication between Tomcat servers and the Apache Web Server that will receive the client requests.

The mod_jk module is distributed separately from Apache HTTPD as part of the Tomcat project. Binary distributions of the module are available for most major platforms, and can be downloaded here. If the version and platform you are looking for is not yet available as a binary distribution, you can build the appropriate version from the source.

Once you have either downloaded and unzipped or built the module, place it in the ‘modules’ directory of your Apache HTTPD server.

Step 3 – Configure mod_jk

Next, we’ll have to set up the mod_jk module in Apache HTTPD’s configuration files. This configuration is a two step process, and can be a little confusing, as mod_jk does not separate its proxy capabilities from its load balancing capabilities.

First, let’s configure the module itself. This is done by adding a few lines to the main Apache HTTPD configuration file, httpd.conf. Take a look at this example configuration (we’ll explain what each attribute does in a second):


# Load module

LoadModule jk_module path/to/apache2/mod_jk.so

# Specify path to worker configuration file

JkWorkersFile /path/to/apache2/conf/workers.properties

# Configure logging and memory

JkShmFile /path/to/desired/log/location/mod_jk.shm

JkLogFile /path/to/desired/log/location/mod_jk.log

JkLogLevel info

# Configure monitoring

JkMount /jkmanager/* jkstatus

<Location /jkmanager>

Order deny, allow

Deny from all

Allow from localhost

</Location>

# Configure applications

JkMount /webapp-directory/* LoadBalancer

Here’s a quick explanation of the parameters we just configured.

  • LoadModule – this command makes the mod_jk module available for use. The extension of the module itself will vary by operating system.
  • JkWorkersFile – sets the path to the worker configuration file, which we will create in the next step.
  • JkShmFile – sets the path to the shared memory files for the module. Generally, you’ll want to keep this with the logs.
  • JkLogFile – sets the path to the module log file.
  • JkLogLevel – sets the level of logging for the module. The valid values for this attribute, in descending order by verbosity, are “debug”, “error” or “info”.
  • JkMount – this is used to map a certain URL pattern to a specific worker configured in the worker configuration file. Here, we use it twice – once to enable /jkmanager as the access URL for jkstatus, a virtual monitoring worker, and once to map all requests we want to be handled by the cluster to the “lb” worker, a virtual worker that contains the load balancing capability
  • Location – this is a security constraint. The settings we have included allow access to the jkmanager only from the localhost (this is a Good Idea).

Step 4 – Configure the cluster workers

Now that we’ve configured the main settings, we will configure the workers. “Workers” is a blanket term used within mod_jk to refer to both real Tomcat servers that will process requests, and virtual servers included in the module to handle load balancing and monitoring. In other words, rather than creating a separate apparatus to manage load balancing, mod_jk simply loads an additional virtual worker with load balancing functionality. If this seems confusing to you, you’re not alone – this is one area where mod_jk shows its age compared to mod_proxy, which keeps all of its configuration in the main httpd.conf file, and doesn’t use the concept of virtual workers.

Here’s a (very) basic workers.properties configuration example (see below for an explanation of the configuration directives):


# Define worker names

worker.list=jkstatus, LoadBalancer

# Create virtual workers

worker.jkstatus.type=status

worker.loadbalancer.type=lb

# Declare Tomcat server workers 1 through n

worker.worker1.type=ajp13

worker.worker1.host=hostname

worker.worker1.port=8009

# …

worker.worker[n].type=ajp13

worker.worker[n].port=8010

worker.worker[n].host=hostname

# Associate real workers with virtual LoadBalancer worker

worker.LoadBalancer.balance_workers=worker1,worker2,…worker[n]

Here’s a quick explanation of the directives we just configured:

Global Directives

These are directives that apply to the entire configuration. There are only two of these directives, and here, we only use one.

worker.list – Allows you to specifically name any workers that should be loaded when the server starts up. These are the only workers to which you can map requests in httpd.conf. This has more uses when using mod_jk as a proxy server. For our purposes, the two workers we’ve defined are enough.

General Worker Directives

These are directives that pertain specifically to workers, but not to virtual workers. They always take the following form:

worker.[name].[directive]=[value]

Worker names are defined as part of a directive (unless set in worker.list). Subsequent directives using the same name value will apply to the same worker. Names may only contain underscores, dashes, and alphanumeric characters, and are case sensitive.

There is a very long list of worker directives, allowing configuration of everything from session replication partner nodes, to connection timeout values, to weights for use with load balancing algorithms. It’s even possible to include workers within multiple nodes, allowing you to do things such as using a very fast server as a pinch hitter to handle spikes in multiple clusters. The extensive control this provides over load balancing scenarios is the reason why using mod_jk over mod_proxy is currently worth the extra configuration trouble. As this is a simple tutorial, we won’t go into the list here, but you can find the whole thing on the Apache project site, and it is highly recommended reading.

worker.[name].type – This allows you to declare a “type” for a given worker. This type can either refer to a virtual worker type (i.e. “lb” for load balancer worker, “status” for the status worker), or to the protocol that the server should use to communicate with a real worker.

Here, we use the type ajp13, which refers to the latest version of the Apache Jserv Protocol, as well as the “lb” and “status” types, which define the virtual load balancing and status manager workers.

worker.[name].host – this allows you to define the appropriate host for a worker. You can also include port in this entry by separating the host name from the port value with a “:”.

worker.[name].port – This allows you to set a port number to access the relevant server. This is especially useful if you want to cluster multiple Tomcat instances running on a single server.

Load Balancer Directives

The mod_jk virtual workers each have their own specialized subsets of directives, which provide extra levels of control over their functions. For example, although the “lb” worker uses a load balancing algorithm based on requests and each server’s lbfactor to distribute the load by default, mod_jk actually includes three additional load balancing algorithms, some of which are more appropriate for certain situations, and can be configured with the “method” directive.

As this is a bare-bones example configuration, we haven’t configured any non-required directives, but as with the worker directives, the full list is available on the Tomcat Connectors project site, and is recommended reading.

worker.[name].balance_workers=[name1],[name2],…[name[n]] – this is the only required load balancer directive, and is used to associate a group of workers with a given load balancer. You can define multiple load balancer names in the global worker list if you will be balancing multiple clusters with a single Apache instance.

If you’d like to learn more about load balancing with mod_jk, visit the load balancing how-to article on the Apache site.

Tips and Tricks

In the interest of simplicity, we’ll leave it up to you to explore the other configuration options on your own. However, before we move on, here’s two quick tricks that can be real time-savers when you start configuring your real-world clusters.

Variables

The mod_jk worker configuration file supports the use of variables to make adding new clusters or migrating configurations to a new server an easier process. Variables can be used in place of any directive-defined value. It’s very simple to define a variable. Simply use the format below, making sure that you do not use a word already associated with a specific function:

[variable_name]=[value]

Variable names can contain any alphanumeric character, as well as dashes, underscores, and periods, and are not case sensitive. To call a variable, use the following syntax:

worker.[name].directive=$(variable_name)

For example, you could define a base network address:

mynetwork=193.228.43

…And then use it to configure multiple workers:


worker.worker1.host=$(mynetwork).12

worker.worker2.host=$(mynetwork).13

worker.worker3.host=$(mynetwork).14

Property Inheritance

If you are configuring multiple similar workers or clusters, you can use the “reference” directive to cause a worker to inherit any properties of another existing worker for which you have not provided an explicit value for the new worker. References are inherited by hierarchy, so you can even create multiple subclasses of reference worker. Use the following syntax to create a reference:

worker.worker1.reference=worker.WorkerTemplate

This will cause “worker1” to inherit all the properties of the “WorkerTemplate” worker. You can create a template worker simply by defining it in the usual way and excluding it from workers.list and any balanced_worker lists. A common use for the reference directive is to define a single load balancer, and use inherited values to split its workers across two domains.

Putting It All Together

A good combined use of property inheritance and variables would be to comment a section at the top of the mod_jk configuration section of your httpd.conf file as “Global Settings and Templates”, and then use something like this:


# Global Settings

myHost=my/host/name.domain

myOtherHost=my/other/hostname.domain

worker.default.connection_timeout=1

worker.default.host=$(myHost)

worker.fastserver.lbfactor=4

worker.fastserver.host=$(myOtherHost)

Using this technique, you can create whole cluster profiles simply by referencing these archetypes, and migrate entire configurations to new servers by changing just a few variables.

For a more in-depth look at defining workers, and some more inspiration for tricky configurations, visit the Workers HowTo [http://tomcat.apache.org/connectors-doc/generic_howto/workers.html] article on Apache’s website.

Step 5 – Configure your Tomcat workers

Now that we’ve finally gotten the mod_jk configuration out of the way, it’s time to configure our Tomcat instances to support clustering. To make this task a little easier to swallow, we’ve divided the process into two steps – enabling session replication, and configuring the actual cluster.

Step 5a – Configure your Tomcat workers – Enabling session replication

In this example, we’ll use simple all-to-all in-memory session replication. This means every worker in our example cluster will replicate their sessions across every other worker. This is not always the most efficient method of session replication in higher load environments, but you can easily build on the concepts we’ll introduce in this section to create a more specific solution when you design clusters for your production environment.

Tomcat provides in-memory session replication through a combination of serializable session attributes, “sticky sessions”, which are provided by the load balancer, and specialized components configured in Tomcat’s XML configuration files. We’ll tackle each of these components one by one.

Serializable Session Attributes

In order to use Tomcat’s built-in session replication, any session attribute or class that will need to be available in the event of failover must implement java.io.Serializable. This interface allows the JVM to convert session objects into bytecode that can be stored in memory and copied to other instances. All JavaBeans are technically required to be serializeable by default, but you should make sure that all your session attributes properly implement the interface.

Sticky Sessions

Load balancers use a variety of methods to make sure that requests are sent to the machine that has the most current session data. The easiest of these, and the one we will use for this example, is called “sticky sessions”.

A load balancer with sticky sessions enabled, after routing a request to a given worker, will pass all subsequent requests with matching sessionID values to the same worker. In the event that this worker fails, the load balancer will begin routing this request to the next most available server that has access to the failed server’s session information. Tomcat’s method of in-memory session replication relies on sticky sessions for both normal and failover load balancing situations.

The latest version of mod_jk enables sticky sessions by default. If you want to be absolutely sure that sticky sessions is enabled for your configuration, you can add the worker.lb.stickysessions=true attribute to your workers.properties file.

Make Your Applications Distributable

In the context of clustered Java application servers, the term “distributable” is used to denote an application that allows its information to be distributed to more than one JVM. This is essential for session replication. You can mark your applications as “distributable” in one of two places. First, you can include the <distributable> element in your application’s deployment descriptor (WEB-INF/web.xml), like this:

<distributable />

Note that the distributable element is one of the rare “self-closing” XML tags in Tomcat; nest it anywhere inside the enclosing <web-app> elements.

Your other option is to simply add the “distributable” attribute to the relevant application’s Context element, as follows:

<Context distributable=”true”>

Even if you have marked your application as distributable, you may run into problems if you haven’t created your web application with clustering in mind. In addition to being declared as such, distributable applications must satisfy the following requirements:

Session attributes must implement java.io.Serializable.

HttpSession.setAttribute() must be called any time changes are made to an object that belongs to a session, so that the session replicator can distribute the changes across the cluster

The sessions must not be so big that they overload the server with traffic when copied.

Setting jvmRoute

The jvmRoute attribute of the Engine element allows the load balancer to match requests to the JVM currently responsible for updating the relevant session. It does this by appending the name of the JVM to the JSESSIONID of the request, and matching this against the worker name provided in workers.properites.

In order to configure jvmRoute, make sure that the value of “jvmRoute” for all your Engines is paired with an identically named Worker name entry in mod_jk’s worker.properties configuration file.

Keeping your Workers in Sync

When clustering multiple servers, it is important that each worker in the cluster have the same understanding of real world time, as some of Tomcat’s clustering features are time-dependent.

In order to eliminate this concern, make sure that all of your servers update their time settings automatically by connecting to the same Network Time Protocol (NTP) service. This is a function of the server OS itself, not of the Tomcat instance. If you are unsure of how to set up this connection, consult the documentation provided by your OS vendor. You can find a list of NTP servers and more information about the service at the NTP Project Wiki.

Step 5b – Configure your Clusters

Finally, you can now configure your cluster to work with Tomcat. This is done in Tomcat’s main configuration file, server.xml, which can be found in the $CATALINA_HOME/conf directory, within a special Cluster element. The cluster element is nested

As not every server configuration requires clustering, the Cluster element is commented out by default. Open server.xml and uncomment the following entry:


<!–

<Cluster className=”org.apache.catalina.ha.tcp.SimpleTcpCluster”/>

–>

The className is the Java class responsible for providing Tomcat’s clustering capabilities, which is included with all versions of Tomcat 5.x and later.

In order to configure clustering, Tomcat uses a mixture of cluster-specific elements and standard Tomcat elements nested within a Cluster element. Let’s take a look at an example cluster configuration, and go through it element by element to learn how it works.

Note that as the goal of this article is simply to demonstrate an easy cluster configuration, we will not get into much depth as to way in which the various Java components that make up Tomcat’s clustering functionality work. However, as you become more familiar with clustering, this is recommended reading, and you can get started on the Apache project site.

An Example Clustering Configuration


<Engine name=”Catalina” defaultHost=”www.mysite.com” jvmRoute=”[worker name]”>

<Cluster className=”org.apache.catalina.ha.tcp.SimpleTcpCluster” channelSendOptions=”8″>

<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″/>

<Sender className=”org.apache.catalina.tribes.transport.ReplicationTransmitter”>

<Transport className=”org.apache.catalina.tribes.transport.nio.PooledParallelSender”/>

</Sender>

<Receiver className=”org.apache.catalina.tribes.transport.nio.NioReceiver”

address=”auto” port=”4000″ autoBind=”100″

selectorTimeout=”5000″ maxThreads=”6″/>

<Interceptor className=”org.apache.catalina.tribes.group.interceptors.TcpFailureDetector”/>

<Interceptor className=”org.apache.catalina.tribes.group.interceptors.MessageDispatch15Interceptor”/>

</Channel>

<Valve className=”org.apache.catalina.ha.tcp.ReplicationValve” filter=””/>

<Valve className=”org.apache.catalina.ha.session.JvmRouteBinderValve”/>

<ClusterListener className=”org.apache.catalina.ha.session.JvmRouteSessionIDBinderListener”/>

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

</Cluster>

Let’s go through this configuration one Element at a time.

Engine

This is the standard Engine element that defines Catalina as the component responsible for processing requests. As we mentioned in Step 5a, to enable session replication, you must set the “jvmRoute” attribute to match the corresponding worker you have configured in mod_jk’s workers.properties file. This value must be unique for every node included in the cluster.

Cluster

This is the main Cluster element, within which all other clustering elements are nested. It supports a variety of attributes, but in this simple example, we have only configured one, “channelSendOptions”. This attribute sets a flag within Tomcat’s clustering class that chooses between different methods of cluster communication. These options are outside the scope of this article, but a safe default setting is “8”, which enables asynchronous communication.

Manager

This is the standard element that Tomcat uses for session management. When nested inside the Cluster element, it is used to tell Tomcat which cluster-aware session manager should be used for session replication. In this example, we have used the DeltaManager, which provides basic cluster-aware session management, as well as additional capabilities you can use to divide your cluster into multiple groups in the future. The attributes we have configured, “expireSessionsOnShutdown” and “notifyListenersOnReplication”, have been configured to prevent a failing node from destroying sessions on other clustered nodes and explicitly notify the ClusterListeners when a session has been updated.

Channel

This element communicates with a component of Tomcat’s clustering solution called Tribes. This component handles all communication between the clustered nodes. In this example, we have configured Tribes to use multicast communication, although more complicated situations can be configured using single point broadcasting. The Channel element is used to contain a series of other elements that divide cluster communication into simple blocks.

Membership

This Tribes-related element defines the address all nodes will use to keep track of one another. The settings we have used here are the Tribes defaults.

Sender

This Tribes-related element, in conduction with the Transport element nested inside of it, is used to choose from and configure a number of different implementations of cluster communication. Here, we have used the NIO transport, which generally provides the best performance.

Receiver

This Tribes-related element configures a single Receiver component, which receives messages from other nodes’ Sender components. The attributes of the element allow you to specify addresses, buffer sizes, thread limits, and more. The settings we have used here allow the nodes to automatically discover one another via an address that Tribes will generate automatically.

Interceptor

Interceptor elements are used to make modifications to messages sent between nodes. For example, one of the Interceptor elements we have configured here detects delays that may be preventing a member from updating its table due to timeout, and provides an alternative TCP connection. Tribes includes a number of standard interceptors; to enable any of them, simply add an addition Interceptor element with the appropriate className. Here, we have included only interceptors useful in almost all clustering situations.

Valve

Tomcat’s standard Valve element can be nested within Cluster elements to provide filtering. The element includes a number of cluster-specific implementations. For example, one of the Valves we have included here can be used to restrict the kinds of files replicated across the cluster. For this example configuration, we have included the most commonly used Valves, with blank attribute values that you can configure as required.

ClusterListener

This element listens to all messages sent through by cluster workers, and intercepts those that match their respective implementation’s specifications. These elements operate in a very similar manner to Inteceptor elements, except that rather than modifying messages and passing them on to a Receiver, they are the intended recipient of the messages for which they are listening.

Once you have edited your server.xml file, simply restart the server, and you will have a cluster-enabled Tomcat instance up and running! Note that you will need to add this configuration to each Tomcat instance you wish to add to the cluster as a worker, and that each Engine element must have its own unique jvmRoute.

How to configure external Tomcat in Myeclipse

MyEclipse->Preferences->Servers, expand the list of servers and then expand the list of Tomcat servers, select the server you’re interested in. On the main configuration panel, click the first Browse button, next to the “Tomcat home directory” text box and select the directory in which you’ve installed Tomcat. The rest of the needed configuration will be filled in. You can add optional program arguments and there are further panels below the main one for adding other options settings.

Don’t forget to select “Enable” at the top of the main configuration panel, otherwise the server won’t appear in the list you mentioned, then click OK.

How can I configure Tomcat with multiple virtual hosts?

Original Post/ Curtsy: 

http://www.ramkitech.com/2012/03/virtual-host-apache-httpd-server-tomcat.html

Thanks to Mr. 

Understanding Virtual Host Concept in Tomcat

Hi in this post we will see how to setup virtual host in Apache Tomcat server. Virtual Host is in-built feature that allows to deploy multiple website(domains) in single instance of tomcat server. The main benefit in this way is its cost effective.

Scenario:

I am going to deploy 3 website with following domain names in single tomcat


http://www.ramki.com
http://www.krishnan.com
http://www.blog.ramki.com

The following diagram is my outline.

Outline structure of Virtual Host Concept in Tomcat

Here my tomcat IP address 192.168.1.15. or any IP address allocated my ISP. but it should be public IP address.

How all domain names are pointing to my Tomcat?
When we purchase the domain name we need to update the our tomcat IP address to it. like

or we can simulate same DNS Setup through hosts file in both Linux and Windows. In Linux tha file is located at /etc/hosts

Now How Setup Virtual Host Concept?

Before going to setup the virtual host. first take look at the server.xml file in conf folder in tomcat directory.

server.xml

  1. <server port=“8005” shutdown=“SHUTDOWN”>
  2.   <service name=“Catalina”>
  3.        <engine defaulthost=“localhost” name=“Catalina”>
  4.             <host appbase=“webapps” autodeploy=“true” name=“localhost” unpackwars=“true”>
  5.             </host>
  6.        </engine>
  7.    </service>
  8. </server>

here <Engine> tag specified which engine is responsible for executing servlet. Here Catalina is the Engine.
<Host> tag  specify the domain name and web apps base location. here default domain name is localhost and web apps base location is webapps folder in tomcat directory. here name attribute to specify the domain name and appbase attribute to specify the location of domain specific web apps folder path.

Now we need to add more <Host> tags to represent to our domains

<Host name=“www.ramki.com” appbase=“ramki_webapps”/>
<Host name=“www.krishnan.com” appbase=“krishnan_webapps” />
<Host name=“www.blog.ramki.com” appbase=“blog_webapps” />


Then we need to copy the webapps folder in tomcat and paste it anywhere and rename it to ramki_webapps, krishnan_webapps, blog_webapps and update the path in <Host> tag

Modifies server.xml file

  1. <server port=“8005” shutdown=“SHUTDOWN”>
  2.   <service name=“Catalina”>
  3.       <engine defaulthost=“localhost” name=“Catalina”>
  4.          <host appbase=“webapps” autodeploy=“true” name=“localhost” unpackwars=“true”></host>
  5.          <host appbase=“ramki_webapps” autodeploy=“true” name=“www.ramki.com” unpackwars=“true”></host>
  6.          <host appbase=“krishnan_webapps” autodeploy=“true” name=“www.krishnan.com” unpackwars=“true”></host>
  7.          <host appbase=“blog_webapps” autodeploy=“true” name=“www.blog.ramki.com” unpackwars=“true”></host>
  8.     </engine>
  9.   </service>
  10. </server>

Simulate the DNS
Open the /etc/hosts file through root privilege and add following entry

192.168.1.15       http://www.ramki.com
192.168.1.15       http://www.krishnan.com
192.168.1.15       http://www.blog.ramki.com

deploy the websites to respective web apps folder and start the tomcat.

Test:
now open the browser and type http://www.ramki.com then its shows the ramk website content. Other two sites http://www.krishnan.com and http://www.blog.ramki.com works respective webapps.

In above diagram represent when we access http://www.ramki.com the tomcat server consult with server.xml file and serves the files from ramki_webapps directory.

How is Virtual Host Works
Here big question all websites are pointed to same tomcat. How tomcat can distinguished the request. (i.e) how tomcat knows browser requested ramki.com or http://www.krishnan.com

The answer is based Host header field in HTTP request.
when we accssed http://www.ramki.com then browser make HTTP request. and the request look like this

GET / HTTP/1.1 
Host: http://www.ramki.com 
Proxy-Connection: keep-alive 
User-Agent: Mozilla/5.0 (Windows NT 6.2) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11 
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 
Accept-Encoding: gzip,deflate,sdch 
Accept-Language: en-US,en;q=0.8


here Host Field contain domain name
Host: http://www.ramki.com

when tomcat receive the request from any browser, it read the Host field and understand which domain we requested, then consult the server.xml file and delegate to appropriate Host process thread

check my screen cast for setup

How to setup virtualhost in Tomcat

I recently had to configure a couple of different tomcat web applications as virtual hosts each one with its own domain. I was accessing these applications using the URL http://localhost:8080/app1 and http://localhost:8080/app2. The basic intention behind the virtual host setup was to avoid the web application name from the url (app1/app2) and the applications to be accessed using http://www.domain1.com and http://www.domain2.com/ . If there was only one web application I could have achieved it by keeping the web application inside webapps/ROOT folder.

Though I am using Apache as front server which was used to forward the dynamic content request to tomcat, I am not describing the Apache-Tomcat configuration in this article. I have described the Apache-Virtualhost-Tomcat-configuration in another article.

Step 1: Configuring Tomcat server.xml

Add the following entry in server.xml (TOMCAT_HOME/conf/server.xml). This should be added below to <Host name=”localhost” ..>…….</Host>

<Host name="www.domain1.com" appBase="/opt/tomcat/www.domain1.com" unpackWARs="true" autoDeploy="true" xmlValidation="false" xmlNamespaceAware="false"/>

<Host name=”www.domain2.com” appBase=”/opt/tomcat/www.domain2.com” unpackWARs=”true” autoDeploy=”true” xmlValidation=”false” xmlNamespaceAware=”false”/>

Step 2: Deploying the applications

Create folders http://www.domain1.com and http://www.domain2.com inside TOMCAT_HOME. Copy the webapp1 to http://www.domain1.com and webapp2 to http://www.domain2.com. Rename both webapp1 and webapp2 to ROOT (ensure ROOT should be in uppercase).

The following should exist after the completion of step2.

TOMCAT_HOME/www.domain1.com/ROOT/webapp1_contents
TOMCAT_HOME/www.domain2.com/ROOT/webapp2_contents

Step 3: Enabling Tomcat Manager Console for the new hosts

The default tomcat manager console (http://localhost:8080/manager/html) will not be available for the new hosts. Manager Console needs to be enabled for the application deployed under each virtual host. This can be done by following the below steps.

Create folders http://www.domain1.com and http://www.domain2.com under TOMCAT_HOME/conf/Catalina/. Copy manager.xml from TOMCAT_HOME/conf/Catalina/localhost/ to TOMCAT_HOME/conf/Catalina/www.domain1.com/ and TOMCAT_HOME/conf/Catalina/www.domain1.com/.

The tomcat manager console for the hosts http://www.domain1.com and http://www.domain2.com can be accessed using the URLs http://www.domain1.com:8080/manager/html and http://www.domain2.com:8080/manager/html respectively.

Step 4: Adding host entry for each virtualhost

In production/staging environments normally the domain would be mapped to the IP of the machine. However in development environments we need to map the IP with the virtualhost. This can be done by adding a host entry in the host file. The ‘hosts’ file is typically located at C:\WINDOWS\system32\drivers\etc\hosts on windows and /etc/hosts on UNIX

Machine-IP http://www.domain1.com
Machine-IP http://www.domain2.com

Step 5: verifying the virtualhosts

Restart the Tomcat Server and check whether the webapp1 and webapp2 are accessible using the URLs http://www.domain1.com:8080 and http://www.domain2.com:8080 respectively.

If you are using Apache web server and Tomcat, you can leave Tomcat running on port 8080. Otherwise simply change the port of tomcat from 8080 to 80.

With Tomcat running on JVM Host dedicated JVM you have full control over configuration files. You may host multiple domains and map them to particular web applications. First step is to map a domain or a directory under it to the Tomcat (this is done with mod_jk or mod_proxy_ajp using our JVMCP control panel), second step is to add virtual host in server.xml. See the below example.

You have 2 domains: primary domain domain1.com and addon domain domain2.com. Your ~/appservers/apache-tomcat/webapps directory:

$ls -al
docs
domain1
domain2
examples
manager
host-manager
ROOT

Please put JSP files into domain1 and domain2 directories. Alternatively you can put domain1.war and domain2.war in webapps directory and Tomcat will deploy the wars.

  1. Domain1.com is the main domain (the main domain can point to different directory such as ROOT, anyway this is only example).
  2. Domain2.com is the domain that we want to add to Tomcat.
  3. You need create domain2.com as addon domain in cPanel.
  4. Please make sure you use correct nameservers for domain2.com.
  5. Create mappings – default mappings are enough. Use custom JVM control panel JVMCP for this.
  6. Configure $CATALINA_HOME/conf/server.xml file.

Please edit $CATALINA_HOME/conf/server.xml

 <Host name="domain1.com" autoDeploy="true" appBase="webapps" unpackWARs="true">
 <Alias>www.domain1.com</Alias>
 <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"   
                prefix="localhost_access_log." suffix=".txt" 
                pattern="%h %l %u %t "%r" %s %b" resolveHosts="false"/>
 <Context path="" docBase="domain1" debug="0" reloadable="true"/> 
 </Host>

 <Host name="domain2.com" autoDeploy="true" appBase="webapps" unpackWARs="true">
 <Alias>www.domain2.com</Alias>
 <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"   
                prefix="localhost_access_log." suffix=".txt" 
                pattern="%h %l %u %t "%r" %s %b" resolveHosts="false"/>
 <Context path="" docBase="domain2" debug="0" reloadable="true"/> 
 </Host>

Restart Tomcat using JVMCP or shell and your are done.

– See more at: http://www.jvmhost.com/articles/how-to-configure-tomcat-with-multiple-virtual-hosts#sthash.Yw1C4fx0.dpuf

With Tomcat running on JVM Host dedicated JVM you have full control over configuration files. You may host multiple domains and map them to particular web applications. First step is to map a domain or a directory under it to the Tomcat (this is done with mod_jk or mod_proxy_ajp using our JVMCP control panel), second step is to add virtual host in server.xml. See the below example.

You have 2 domains: primary domain domain1.com and addon domain domain2.com. Your ~/appservers/apache-tomcat/webapps directory:

$ls -al
docs
domain1
domain2
examples
manager
host-manager
ROOT

Please put JSP files into domain1 and domain2 directories. Alternatively you can put domain1.war and domain2.war in webapps directory and Tomcat will deploy the wars.

  1. Domain1.com is the main domain (the main domain can point to different directory such as ROOT, anyway this is only example).
  2. Domain2.com is the domain that we want to add to Tomcat.
  3. You need create domain2.com as addon domain in cPanel.
  4. Please make sure you use correct nameservers for domain2.com.
  5. Create mappings – default mappings are enough. Use custom JVM control panel JVMCP for this.
  6. Configure $CATALINA_HOME/conf/server.xml file.

Please edit $CATALINA_HOME/conf/server.xml

 <Host name="domain1.com" autoDeploy="true" appBase="webapps" unpackWARs="true">
 <Alias>www.domain1.com</Alias>
 <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"   
                prefix="localhost_access_log." suffix=".txt" 
                pattern="%h %l %u %t "%r" %s %b" resolveHosts="false"/>
 <Context path="" docBase="domain1" debug="0" reloadable="true"/> 
 </Host>

 <Host name="domain2.com" autoDeploy="true" appBase="webapps" unpackWARs="true">
 <Alias>www.domain2.com</Alias>
 <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"   
                prefix="localhost_access_log." suffix=".txt" 
                pattern="%h %l %u %t "%r" %s %b" resolveHosts="false"/>
 <Context path="" docBase="domain2" debug="0" reloadable="true"/> 
 </Host>

Restart Tomcat using JVMCP or shell and your are done.

– See more at: http://www.jvmhost.com/articles/how-to-configure-tomcat-with-multiple-virtual-hosts#sthash.Yw1C4fx0.dpuf

http://www.jvmhost.com/articles/how-to-configure-tomcat-with-multiple-virtual-hosts

How to create virtual host for app on Tomcat.

NB! I will say right away, that my Tomcat is running on Ubuntu Server 10.10 under VMWare Workstation 7.
So here it goes. Recently I installed YouTrack issue tracker on my local server, that runs on Tomcat. Very soon I got tired from typing every time (ip_address/webapp_name:port). So I looked up how to create a very simple VirtualHost for Tomcat.

To create Tomcat VirtualHost you just need to edit tomcat_dir/conf/server.xml and inside Engine tag place following code:

1
2
3
4
5
<Host name="virtual_host_name" appBase="webapps/your_app_name" unpackWars="false" autoDeploy="false">
    <Logger className="org.apache.catalina.logger.FileLogger" directory="logs" prefix="virtual_log." suffix=".txt" timestamp="true" />
    <Context path="" docBase="path_to_your_webapp_from_root" debug="0" reloadable="true" />
    <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" prefix="virtual_log." suffix=".txt" pattern="common" />
</Host>

So in the end you will have to add this virtual_host_name to your windows hosts file and link to your VM ip address. Then you will be abble to access your like: virtual_host_name:8080.

With Tomcat running on JVM Host dedicated JVM you have full control over configuration files. You may host multiple domains and map them to particular web applications. First step is to map a domain or a directory under it to the Tomcat (this is done with mod_jk or mod_proxy_ajp using our JVMCP control panel), second step is to add virtual host in server.xml. See the below example.

You have 2 domains: primary domain domain1.com and addon domain domain2.com. Your ~/appservers/apache-tomcat/webapps directory:

$ls -al
docs
domain1
domain2
examples
manager
host-manager
ROOT

Please put JSP files into domain1 and domain2 directories. Alternatively you can put domain1.war and domain2.war in webapps directory and Tomcat will deploy the wars.

  1. Domain1.com is the main domain (the main domain can point to different directory such as ROOT, anyway this is only example).
  2. Domain2.com is the domain that we want to add to Tomcat.
  3. You need create domain2.com as addon domain in cPanel.
  4. Please make sure you use correct nameservers for domain2.com.
  5. Create mappings – default mappings are enough. Use custom JVM control panel JVMCP for this.
  6. Configure $CATALINA_HOME/conf/server.xml file.

Please edit $CATALINA_HOME/conf/server.xml

 <Host name="domain1.com" autoDeploy="true" appBase="webapps" unpackWARs="true">
 <Alias>www.domain1.com</Alias>
 <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"   
                prefix="localhost_access_log." suffix=".txt" 
                pattern="%h %l %u %t "%r" %s %b" resolveHosts="false"/>
 <Context path="" docBase="domain1" debug="0" reloadable="true"/> 
 </Host>

 <Host name="domain2.com" autoDeploy="true" appBase="webapps" unpackWARs="true">
 <Alias>www.domain2.com</Alias>
 <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"   
                prefix="localhost_access_log." suffix=".txt" 
                pattern="%h %l %u %t "%r" %s %b" resolveHosts="false"/>
 <Context path="" docBase="domain2" debug="0" reloadable="true"/> 
 </Host>

Restart Tomcat using JVMCP or shell and your are done.

– See more at: http://www.jvmhost.com/articles/how-to-configure-tomcat-with-multiple-virtual-hosts#sthash.Yw1C4fx0.dpuf

Howto Install Tomcat 7 on Debian (Lenny/ squeeze/ wheeze)

This Article describes how to install Apache Tomcat 7 on a Debian (Lenny) OS in 8 easy steps.
For this HowTo to work smoothly you must already have Java installed on your machine. In case you haven’t Java installed on your machine, there is anoter HowTo for this Task on my Blog. Follow the instructions in thisPost and come back when Java is up and running.

1. Download it!

The first step is to aquire Tomcat 7 by downloading it from the Homepage. This is really easy, I used wget to download the “apache-tomcat-7.0.2.tar.gz” archive into my /temp Directory. This should look something like this:

2. Unzip & Move

Move the package to it’s permanant location and unzip the package into its own folder.

1
2
mv apache-tomcat-7.0.2/ /usr/local/tomcat
tar -zxvf apache-tomcat-7.0.0.tar.gz

3. Create “tomcat” Group & User

Next you need to add a new group and a new user to your system. This will be the user and the group under which the Tomcat server runs.

1. To add a group called “tomcat” you simply type:

1
groupadd tomcat

2. Now you have to create a new user called “tomcat” (useradd tomcat) who belongs to the group “tomcat” (-g tomcat). You also should set the home directory of that user to the directory where you moved the Tomcat server in the previous step. In this case that would be “/usr/local/tomcat” (-d /usr/local/tomcat). So you should end up with a statement that looks something like this:

1
useradd -g tomcat -d /usr/local/tomcat tomcat

3. Now you should also add the user to the “www-data” group. This group should already exist. You do that by executing the following command:

1
usermod -G www-data tomcat

4. Create INIT File for Tomcat

Now you should create an INIT-File that makes it possible to start, stop and restart your Tomcat Server. This file must be located in your “/etc/init.d/” directory. You can use the following command to create a file called “tomcat” and open up that file in an editor (I used nano).

1
nano /etc/init.d/tomcat

Now you should add the following lines into the file an save it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#Tomcat auto-start
#description: Auto-starts tomcat
#processname: tomcat
#pidfile: /var/run/tomcat.pid
#this path should point to your JAVA_HOME Directory
export JAVA_HOME=/usr/lib/jvm/java-6-sun
case $1 in
start)
  sh /usr/local/tomcat/bin/startup.sh
  ;;
stop) 
  sh /usr/local/tomcat/bin/shutdown.sh
  ;;
restart)
  sh /usr/local/tomcat/bin/shutdown.sh
  sh /usr/local/tomcat/bin/startup.sh
  ;;
esac
   
exit 0

Make sure you set the right paths for the startup.sh and shutdown.sh scripts. They reside in the /bin directory of your tomcat path (use the path to which you moved the tomcat files in step 2).

5. Adjust Permissions of INIT File

Since you have to execute the tomcat file, you have to assign the correct rights for the file to be executable.
This line should do the trick:

1
chmod 755 /etc/init.d/tomcat

6. Make Tomcat auto-start on boot (optional)

If you want the Tomcat Server to start every time the system boots up you can use the “update-rc.d” command to set a symbolic link at the correct runlevel. For the “tomcat fle” this looks like this:

1
update-rc.d tomcat defaults

Now the Tomcat Server starts automatically at system bootup. This step is optional you can always start your Tomcat Server manually like this:

1
/etc/init.d/tomcat start

7. Modify Tomcat Users File

We are almost there! In this step we need to add a user in the tomcat-users.xml. This user is used to gain access to the Tomcat Manager Interface in the next step. So open up the “tomcat-users.xml” file with any editor you like (i used nano):

1
nano /usr/local/tomcat/conf/tomcat-users.xml

There is a <tomcat-users> section within that file. After the installation this section should only contain comments and look something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<tomcat-users>
<!--
  NOTE:  By default, no user is included in the "manager-gui" role required
  to operate the "/manager/html" web application.  If you wish to use this app,
  you must define such a user - the username and password are arbitrary.
-->
<!--
  NOTE:  The sample user and role entries below are wrapped in a comment
  and thus are ignored when reading this file. Do not forget to remove
  <!.. ..> that surrounds them.
-->
<!--
  <role rolename="tomcat"/>
  <role rolename="role1"/>
  <user username="tomcat" password="tomcat" roles="tomcat"/>
  <user username="both" password="tomcat" roles="tomcat,role1"/>
  <user username="role1" password="tomcat" roles="role1"/>
-->
</tomcat-users>

Now all we need to do is add a new user by adding some new lines here. After insertion the section should look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<tomcat-users>
<!--
  NOTE:  By default, no user is included in the "manager-gui" role required
  to operate the "/manager/html" web application.  If you wish to use this app,
  you must define such a user - the username and password are arbitrary.
-->
<!--
  NOTE:  The sample user and role entries below are wrapped in a comment
  and thus are ignored when reading this file. Do not forget to remove
  <!.. ..> that surrounds them.
-->
<!--
  <role rolename="tomcat"/>
  <role rolename="role1"/>
  <user username="tomcat" password="tomcat" roles="tomcat"/>
  <user username="both" password="tomcat" roles="tomcat,role1"/>
  <user username="role1" password="tomcat" roles="role1"/>
-->
  <role rolename="manager"/>
  <role rolename="manager-gui"/>
  <role rolename="admin"/>
  <user username="admin" password="tomcat" roles="admin,manager,manager-gui"/>
</tomcat-users>

In lines 19-22 I added three roles with the names “manager”, “manager-gui” and “admin”. In line 22 I created a user with the username “admin”, the password “tomcat” and the roles I created before. This user will be used to access the Tomcat Manager Interface in the next step.

All there is left to do is to restart the Tomcat Server to make him recognize that the “tomcat-users.xml” file has changed and that there is a new user with the name “admin” and the password “tomcat”. This is how you restart your Tomcat Server:

1
/etc/init.d/tomcat restart

8. Test Tomcat Manager Interface

Finally we can check if everything went right. If your Tomcat Server runs on your local machine your can access it via the following adress:

http://localhost:8080/

otherwise you have to replace the “localhost” part with the IP adress or name of your server. This could look like this:

http://192.168.6.15:8080/

If all went right you should see the following site in your browser:

This is the Tomcat Startup Site

Now you know that your Tomcat Server is running. Next we will log in to the Tomcat Manager Interface. For that you should click on the link that says “Tomcat Manager” in the upper left part of the webpage (This link is actually highlighted in the picture above.). Now you will be prompted for your username and password. Type in the username and the password you set in the “tomcat-users.xml” file (in this case that would be “admin” and “tomcat”)

Tomcat Manager Username and Password Prompt

After that you should see the site of the Tomcat Manager.

The Tomcat Manager Interface

Congratulations you just installed your very own Tomcat Server.

Let me know what you think about my article. Perhaps there are some sections where i need to be a little bit more elaborate. Just drop me a line….