Expand the capabilities of your Tomcat Web server

Take your server to the next level

This tutorial is a must-have guide for any Web or application server administrator. Although the implementations are slightly different from Apache Tomcat and other Web servers, this tutorial breaks down in a logical and concise way many advanced administrative tasks necessary for successfully hosting, deploying, and managing multiple Java™ 2 Platform, Enterprise Edition (J2EE) Web applications. Learn how to set up, configure, and secure your Tomcat server, and discover tips and tools for advanced deployment considerations.

Matthew Skamser, Software Consultant, Solution Destination, Inc.

author photoMatthew L. Skamser is an IT consultant and Studio B author with more than 10 years of experience architecting, administering, troubleshooting, and tuning Web applications in enterprise server environments. His clients have included IBM, Lockheed Martin/United States Air Force, and WorldBank. He has multiple IBM Certified Systems Expert certifications and received his bachelor's degree in Computer Information Systems from Northern Arizona University. You can reach Matthew at matt@solutiondestination.com.



16 September 2008

Before you start

Learn what to expect from this tutorial and how to get the most out of it.

About this tutorial

If you're taking this tutorial, you probably already have an existing Apache Tomcat base stand-alone Web server installed. If not, please take the previous tutorial, "Install and configuring a development Web server in UNIX," first. Then, you can come back to this tutorial to learn more about the advanced features and options with which you can configure that server, along with detailed steps for implementing them.

If, however, you're simply curious about certain Web server administration techniques that may universally cross over from one Web server environment to another, just want some additional knowledge about the Tomcat product itself, or would like to pick up a few administrative tips, read on.

Objectives

In this tutorial, you will find:

  • An introduction to why you would need to configure some of these advanced settings for your existing Web server, the target audience this tutorial addresses, and a summary of the details that the tutorial provides, including prerequisites for beginning the tutorial.
  • Contrast between the limitations of a base Tomcat Web server versus one with greater security, robustness, and expandability.
  • An overview of deploying advanced applications in Tomcat.
  • Security considerations, including step-by-step setup, installation, and configuration procedures for Tomcat for features such as the Java™ Security Manager and Secure Sockets Layer (SSL).
  • Databases and data source connections from your Tomcat server.
  • Advanced Tomcat administrative tips.
  • Additional resources.

Prerequisites

This tutorial assumes that you have already installed the base UNIX® operating system of your choice. To run the examples in this tutorial, you must also have Tomcat version 6 installed and running.

System requirements

Your server should have at least 10GB of available hard disk space and a minimum of 512MB of RAM. You need the following additional tools installed on your UNIX server before you can begin:


What you need to know

Discover what you need to know to make the right configuration and customization decisions for your Tomcat environment.

Base versus advanced setup

Obviously, installing Tomcat and getting the sample application up and running is just the beginning. You built the foundation: Now, you must unlock the true power of this simple, free, and effective server software. Besides, you will definitely want to secure your server and learn a few things about setting up a database and troubleshooting it if problems occur.

If you worked through the previous tutorial, your server is up and running. But even in a test environment, you have your limitations. You must set up the test server so that it's identical to the production server. In the original setup, you did the bare minimum to get up and running—installing and setting up the server software environment and implementing the Tomcat Web Application Manager console to deploy the Tomcat sample application. In this tutorial, you get extensive deployment and security information along with administration tips.

Tomcat in production

Throughout this tutorial, you're free to experiment with advanced middleware administration techniques to ensure the highest level of uptime and stability, which we all know in the corporate world is a top priority! In a production environment, you may have multiple applications being served on the same server accessible by different URLs (virtual hosting), you may have multiple servers in a server farm, many additional deployment needs, and certainly at least basic authentication and SSL set up to protect your application from the outside world. However, have no fear: The remainder of this tutorial is dedicated to empowering you to set up your server for efficiency, security, and future expandability.

Five core questions

Begin by planning the requirements for what the application you're testing will need. Whether this application is an advanced "Hello World" application or some freshly developed masterpiece, you must understand your needs at the development level and how those needs translate into what you must set up at the server level. Or maybe you're an administrator who doesn't care about the code and just needs to set up the server. That's fine, too. Regardless of your role, you'll need answers to the following questions:

  • How do you set up database access, resource references, and so on to match the external or internal dependencies of your application?
  • How can you secure your Tomcat server while implementing standard authentication and other security measures?
  • How do you successfully deploy your application?
  • What are some other administrative and troubleshooting tips to ensure continued success?
  • What are other tips and resources for setting up your server to run production applications?

These questions drive the remainder of this tutorial. You get step-by-step instructions for how to implement the practical solutions necessary to answer the above questions and take your server and skills to the next level.


Application deployment

What good is an application server with no applications?

Advanced application deployment

In the previous tutorial, you learned how to install the simple sample application using the Tomcat Web Application Manager console. However, as fun as that was, it's not a very realistic representation of what you're likely going to encounter on a daily basis. Here, you see how Tomcat works with your application deployment descriptors and relies heavily on contexts. Also, you focus on automatic deployment methods that let Tomcat do most of the work without your having to worry about pulling up a console and going through manual procedures to deploy the application.

With the introduction of the Servlet version 2.2 specification (see Resources), a Web application consists of servlets, Hypertext Markup Language (HTML) pages, classes, and other resources that can be bundled and run on multiple containers from multiple vendors. Of course, you're deploying Java applications on Java-based server technology: Tomcat is not intended for Microsoft® .NET-related code and deployments.

WAR files

You must know how the code is packaged so that you know how to deploy it. When I say packaged, think zipped, archived—whatever you do to compress contents of a directory structure into one file. In this case, you'll be using Web Archive (WAR) files, which carry the .war extension.

Figure 1 shows the basic format of how a Java application is packaged.

Figure 1. Components of a Web module
Web module

Directories

A Web module has a specific structure that doesn't change. The assembly root/document root (called AppBase), contains JavaServer Pages™ (JSP) code pages, client-side classes and archives, and static images. This directory contains a subdirectory named /WEB-INF/, which in turn contains the following files and directories:

  • web.xml: This is the Web application deployment descriptor and a vital piece of the deployment picture. This is also where the application-specific security and role-based definitions reside.
  • lib: This is the library archive folder. It contains Java Archive (JAR) files of libraries that are called by server-side classes.
  • classes: This directory contains the server-side classes—servlets, JavaBean components, and so on.
  • tags: This directory contains the tag files for the Web modules, which are an implementation of the tag libraries.

Contexts

Understanding contexts in Tomcat is a critical prerequisite for moving on with the actual installation of your application. After you create the Web application directory structure, you must add a context for Tomcat to know the application is out there.

The context defines the set of methods that the servlet container uses to communicate with the Web application. The Java 2 Platform, Enterprise Edition (J2EE) standard provides a standard set of elements in the /WEB-INF/web.xml file to reference resources that must be defined in an application server-specific configuration. For Tomcat version 6, these specific Web application entries for InitialContext are configured in the <Context> elements that can be specified in either $CATALINA_HOME/conf/server.xml or the specific Web application context Extensible Markup Language (XML) file (META-INF/context.xml). It is a best practice not to define these contexts in the server.xml file, as was the case in the past. Instead, it's better to separate them by creating and editing the context.xml file.

A context descriptor is simply an XML file that contains Tomcat-related configuration for a context. The InitialContext is configured as a Web application that is initially deployed and is made available to Web application components (for Read-only access).

The locations for context descriptors are typically:

  • $CATALINA_HOME/conf/enginename/hostname/context.xml (for example, $CATALINA_HOME/conf/Catalina/localhost/myApp.xml)
  • $CATALINA_HOME/webapps/myApp/META-INF/context.xml

Quick tips

If a context descriptor is not provided for a context, Tomcat configures the context using default values. You can explicitly define elements for all applications to use under the webapps directory by editing the $CATALINA_HOME/conf/context.xml file.

Listing 1 provides a basic example of an application-specific context.

Listing 1. Example of an application-specific context
<Context docBase="myApp" debug="1" reloadable="true">
<Logger className=""
prefix="localhost_myApp" suffix=".log"
timestamp="false"/>
 <Resource name="jdbc/myApp" auth="Container" 
type="javax.sql.DataSource"/>
 <ResourceParams name="jdbc/myApp">
   <parameter>
       <name>driverClassName</name>
        <value>sun.jdbc.odbc.JDriver</value>
   </parameter>
   <paramete>
       <name>url<name>
        <value>jdbc:odbc:myApp</value>
   </parameter>
 </ResourceParams>
</Contex>

The docBase and all database driver information in this listing will be unique to your application. Remember, the path="" variable under context is not needed unless you're editing the context in the server.xml file, which is not recommended.

This code uses Java Naming and Directory Interface (JNDI) and references your data source driver and class name, both of which are described in detail in the section, Databases. See Resources for more options regarding resource definitions within the <Context> tags.

Auto-deploy

Throughout the explanations of the auto-deploy methods, you'll be referring to your host server (by default, localhost) and the appBase attribute (your default appBase directory is $CATALINA_HOME/webapps).

Deploy on startup

Deploying on startup simply means that you will be manually deploying your static content by means of copying that content (in WAR file format or already expanded) under the $CATALINA_HOME/appbase directory, and then stopping or starting your Tomcat server. To take advantage of the Deploy on Startup feature, you must simply edit your host to set the deployOnStartup attribute to True, as shown in Listing 2.

Listing 2. deployOnStartup.xml
<Engine name="Catalina" defaultHost="localhost" debug="0">
      <!-- This host is the default host. -->
      <Host name="localhost" debug="0" appBase="webapps"
	      unpackWARs="true" autoDeploy="true" deployOnStartup="true">
        <Context path="" docBase="ROOT" debug="0"/>
        </Context>
      </Host>

The deployment is kicked off at startup if one of the following conditions is true:

  • There are new or updated context descriptors in the XML file in the $CATALINA_HOME/conf/engine_name/host_name directory.
  • There is a new expanded application under the appBase directory. In this case, Tomcat checks for an associated WAR file in the appBase directory with the same name that is newer than the expanded Web application. Then, the expanded directory is removed, and the Web application is redeployed from the WAR (assuming unpackWars=true in the host context).
  • Any new WAR files exist in the appBase directory.

In addition to being able to deploy at startup, Tomcat can request that new XML configuration files, WAR files, or subdirectories that are dropped into the appBase directory (or $CATALINA_HOME/conf/engine_name/host_name in the case of an XML configuration file) while Tomcat is running be automatically deployed. You configure this behavior by setting autoDeploy="true" in the context file.

Deploy while running

To enable this helpful feature within Tomcat, set the autoDeploy tag equal to True, as shown in Listing 3.

Listing 3. autoDeploy xml
<Engine name="Catalina" defaultHost="localhost" debug="0">
      <!-- This host is the default host. -->
      <Host name="localhost" debug="0" appBase="webapps"
	      unpackWARs="true" autoDeploy="true" deployOnStartup="true">
        <Context path="" docBase="ROOT" debug="0"/>
        </Context>
      </Host>

The auto-deployer will also track Web applications for the following changes:

  • Updating the WEB-INF/web.xml file triggers a reload of the Web application.
  • Placing an updated WAR file in the appBase directory, which was expanded previously, triggers an "undeploy" (with a removal of the expanded Web application), followed by a deployment.
  • Updating an XML configuration file triggers an "undeploy" (without the removal of any expanded directory), followed by deployment of the associated Web application.

When using automatic deployment, the docBase defined by an XML context file should be outside the appBase directory. If this is not the case, you may experience difficulties when deploying the Web application, or the application may be deployed twice.

Final thoughts on deploying applications in Tomcat

If you're defining contexts explicitly, you should probably turn off automatic application deployment. Otherwise, your context will be deployed twice each, and that may cause problems for your application.

Also, it's sometimes best with Tomcat to remove all old directories before copying and expanding the WAR. Otherwise, it will overwrite certain things while leaving old code instead of reinstalling all as intended. The settings in the server.xml file above should alleviate this problem, but it's better not to take a chance. If your application is acting strange, consider looking at how you redeployed it. This also requires a necessary but annoying restart of Tomcat each time you install something new.

Tomcat Web Application Manager

The Tomcat Web Application Manager, which comes as a part of Tomcat and which you installed in the previous tutorial, has interesting features. It allows you to deploy and administer Web applications through an application installed in the context path /manager (for example, http://localhost:8080/manager). It allows you to deploy, start and stop, list operating system settings, and so on using Hypertext Transfer Protocol (HTTP)-based URL commands locally or remotely, an application graphical user interface (GUI), or even by Apache Ant commands through an Ant build script.

To use the functionality of the automated deployments, you must have your Tomcat Web Application Manager user set up in the tomcat-users.xml file (the default XML file for the Tomcat Web Application Manager application). If you haven't set up the application yet, do so now. Then, add a user and password with the role manager, and restart Tomcat.

Note: If you want to explore the GUI functionality, go to the Tomcat Web Application Manager URL, or click the Tomcat Manager link in the upper left navigation column.

All Uniform Resource Identifier (URI)-based manager commands are specified in a single request URI like this:

http://{host}:{port}/manager/{command}?{parameters}

Useful URL commands

Tomcat Web Application Manager provides several URL commands that you can use to deploy and redeploy an application:

  • Deploy using a URI: To deploy an application using a URI, type the following URL in your Web browser's address bar:
    http://localhost:8080/manager/deploy?path=/sample&
        war=file:$CATALINA_HOME/webapps/docs/appdev/sample/sample.war

    If successful, you should see a message similar to this:

    OK - Deployed application at context path /sample

    You may want to access http://localhost:8080/sample/ just to be sure.

  • Reload the current application: To reload the current application, type the following URL in your Web browser's address bar:
    http://localhost:8080/manager/reload?path=/sample

    This URL signals an existing application to shut itself down and reload. This URL command can be useful when the Web application context is not reloadable and you have updated classes or property files in the /WEB-INF/classes directory or when you have added or updated JAR files in the /WEB-INF/lib directory. However, any changes made to the web.xml file require restarting the application.

    If the command was successful, you should see something like this:

    OK - Reloaded application at context path /sample
  • List operating system and Java Virtual Machine (JVM) properties: To list the operating system and JVM properties, type the following URL in your Web browser's address bar:
    http://localhost:8080/manager/serverinfo

    If the command was successful, you should see something like this:

    OK - Server info
    Tomcat Version: Apache Tomcat/6.0.16
    OS Name: SunOS
    OS Version: 5.10
    OS Architecture: x86
    JVM Version: 1.5.0_12-b04
    JVM Vendor: Sun Microsystems Inc.
  • Start, stop, or undeploy an application: You can start, stop, or "undeploy" an application simply by typing those values in the URL path:
    http://localhost:8080/manager/start?path=/sample
    http://localhost:8080/manager/stop?path=/sample
    http://localhost:8080/manager/undeploy?path=/sample
  • List currently deployed applications: To list the currently deployed applications, type the following URL in your Web browser's address bar:
    http://localhost:8080/manager/list

    If the command is successful, you should see something like this:

    OK - Listed applications for virtual host localhost
    /examples:running:0:examples
    /host-manager:running:0:host-manager
    /sample:running:0:sample
    /docs:running:0:docs
    /manager:running:0:manager
    /:running:0:ROOT

There are a couple of other deployment tools that are good to have in your expanding Tomcat toolbox. Many developers and administrators use Ant specifically and often prefer it over Tomcat Web Application Manager URL administration because of its customizable build script and easy-to-execute commands.

Other deployment tools

Ant and the Tomcat Client Deployer (TCD) are discussed in this section. Both are worthy of further exploration, so see Resources for more information.

Ant

Before you can use Ant, perform the following steps:

  1. Download and install the binary distribution of Ant version 1.4 or later.

    The installation location is under the $ANT_HOME directory, which resides wherever you choose to install it (for example, beneath /opt or /export/home). It may be good to keep this path similar to where you installed your Tomcat server.

  2. Copy the file server/lib/catalina-ant.jar file from your Tomcat version 6 installation into $ANT_HOME/lib.
  3. Add the $ANT_HOME/bin directory to your PATH environment variable so that you don't have to type the full path each time. To do so, type:
    PATH=$ANT_HOME/bin; export PATH

Ant is similar to the make utility used to build and compile Java applications. However, Ant is more powerful and more popular. It can compile the Java source code files, copy class files, and package WAR files.

For Ant to have the access to deploy applications from the command line, it must have a user name and password with manager role access. You can use the same user name and password from Tomcat Web Application Manager (see Tomcat Web Application Manager earlier in this tutorial), and configure that in the XML format shown in Listing 4 in the build.xml file. The build.xml file will be the main file you customize for Ant.

Listing 4. Example build.xml file
<project name="My Application" default="compile" basedir=".">

  <!-- Configure the directory into which the Web application is built. -->
  <property name="build"    value="${basedir}/build"/>

  <!-- Configure the context path for this application. -->
  <property name="path"     value="/myapp"/>
 
<!-- Configure properties to access the Manager application. -->
  
  <property name="url"     value="http://localhost:8080/manager"/>
  <property name="username" value="myusername"/>
  <property name="password" value="mypassword"/>

  <!-- Configure the custom Ant tasks for the Manager application ->
  <taskdef name="deploy"    classname="org.apache.catalina.ant.DeployTask"/>
  <taskdef name="list"      classname="org.apache.catalina.ant.ListTask"/>
  <taskdef name="reload"    classname="org.apache.catalina.ant.ReloadTask"/>
  <taskdef name="resources" classname="org.apache.catalina.ant.ResourcesTask"/>
  <taskdef name="roles"     classname="org.apache.catalina.ant.RolesTask"/>
  <taskdef name="start"     classname="org.apache.catalina.ant.StartTask"/>
  <taskdef name="stop"      classname="org.apache.catalina.ant.StopTask"/>
  <taskdef name="undeploy"  classname="org.apache.catalina.ant.UndeployTask"/>

  <!-- Executable Targets -->
  <target name="compile" description="Compile web application">
    <!-- ... construct web application in ${build} subdirectory, and
            generated a ${path}.war ... -->
  </target>

  <target name="deploy" description="Install web application"
          depends="compile">
    <deploy url="${url}" username="${username}" password="${password}"
            path="${path}" war="file:${build}${path}.war"/>
  </target>

  <target name="reload" description="Reload web application"
          depends="compile">
   <reload  url="${url}" username="${username}" password="${password}"
            path="${path}"/>
  </target>

  <target name="undeploy" description="Remove web application">
    <undeploy url="${url}" username="${username}" password="${password}"
            path="${path}"/>
  </target>

</project>

The taskdef commands in this listing are what you use when executing Ant. To run the Ant commands, you simply type ant start , ant deploy, ant undeploy, and so on. Obviously, you need to hard-code in all the $ variables with similar values to those that you plugged in for Tomcat Web Application Manager, but doing this provides nice shortcuts for common deployment and administrative tasks.

Note: You can create the build.xml file in the main ANT_HOME path. If you try to execute an Ant command without a build.xml file or in a build.xml file in a location that Ant cannot see, you get the following error:

Buildfile: build.xml does not exist!Build failed

When running Ant with the build.xml file, it compiles a Java file present in the /src directory and places compiled class files in the build/src directory.

Tomcat Client Deployer

The TCD is a third-party tool used to validate, compile, compress to WAR, and deploy Web applications to Tomcat servers. A prerequisite to running this tool is to have Ant downloaded and properly installed as discussed in the section, Ant, above. For more information about this tool, see Resources.


Database connections

You know that a database is an essential part of any dynamic Web application that will store, share, or access data of any kind received through sessions, forms, and so on. There is an ever-increasing focus on Web customizations per a client's Web idiosyncrasies, shopping, and browsing patterns using basic and advanced data warehousing. Simple communal interaction between the Web and the user on social, community, or wiki-based sites is yet another reason why one or more databases in even small, basic sites are necessary.

Service-Oriented Architecture (SOA) is increasingly driving information technology (IT) systems based on business process modeling (BPM) and specific client and data statistics. The only way to do that is by having ways to store and retrieve data. This section shows how to connect Tomcat to your database.

Databases

The bare minimum for a database is the database software itself (for example, Oracle, IBM® DB2®, or MySQL) installed on your server. You must also have a user and at least a single test table before you can connect your application to this database in Tomcat.

You also need to have a Java Database Connectivity (JDBC) driver installed. This driver is necessary for managing database calls and connection pools to provide for the greatest efficiency and flexibility in managing the database connections separate from your code.

Install the driver

Drivers, like databases, are software dependent. For Oracle and, likely, DB2, you also need the client installed. Regardless of which driver you use, you must copy the JAR files to CATALINA_HOME/lib. A helpful tip that I've found for doing this is to rename your driver download's file name extension from .zip to .jar. You don't need to do anything but rename it, because .zip and .jar files are the same.

JDBC

The JDBC application program interface (API) is the industry standard for database-independent connectivity between the Java programming language and a wide range of databases.

The JDBC API makes it possible to do three things:

  • Establish a connection with a database or access any tabular data source.
  • Send Structured Query Language (SQL) statements.
  • Process the results.

DBCP

Database Connection Pool (DBCP) is still the standard Tomcat connection pool broker. The commons-dbcp package relies on code in the commons-pool package to provide the underlying object pool mechanisms that it uses. These libraries reside in a single JAR at $CATALINA_HOME/lib/tomcat-dbcp.jar. Applications can use the commons-dbcp component directly or through the existing interface of their container framework.

Note: In older versions of Tomcat, you must place the JDBC JAR for your database driver in the $CATALINA_HOME/common/lib directory. Otherwise, Tomcat won't be able to load the JDBC driver. If there is some problem with Tomcat seeing your driver, copy the files to CATALINA_HOME/common/lib.

When the database is created and your driver is installed, perform the following steps:

  1. Create or map the initial context in the server.xml file in Tomcat.

    Doing so defines the resource in the server.xml file to make sure that your driver can be seen by the base Tomcat installation as well as your Web application. This is the same as manually creating a data source in Tomcat to look up, connect to, and manage those connections.

  2. Create the resource reference in the web.xml file for the application, or make it shared in the server.xml file.
  3. To take advantage of the newly defined JNDI name in your code, use the javax.naming.Context.lookup() method to look up the data source and obtain a database connection.

When those three simple steps are complete, you can test your application.

Create the initial context

The initial context is simply the resource definition defined in the <Context> tags within the server.xml file using JNDI to reference the defined resource. You need to know a bit about JNDI before proceeding further, because it is a foundational J2EE element and comes as an extension to your Java platform.

JNDI is a directory and naming service used to access different—possibly multiple—naming and directory services using a common API. For both the GUI and manual processes of creating your resource reference, you need the information outlined in Table 1.

JNDI

JNDI provides a standard interface for locating users, machines, networks, objects, and services. The naming service allows you to store various types of objects and associate or bind names to these objects. It also provides a facility for searching or looking up an object based on a name.

In general, perform the following steps to look up an object:

  1. Acquire an initial context.
  2. Look up the object using the JNDI name.
Table 1. Prerequisites for creating data source resource definitions
NameDescription
JNDI nameJNDI lookup name for your data source
Data source URLSpecific JDBC reference URL for your data source
JDBC driver classLook up and type your JDBC driver class here (See Resources for more information.)
User nameThe database schema user name
PasswordThe password that you set up for your database user name

Create your resource definition/data source

Creating a resource reference manually is essentially the exact thing you would do if you were to pull up the Tomcat Web Administration Manager console and create a data source in the GUI. To do that (if you're more comfortable pulling up the console), perform the following steps:

  1. Open the Tomcat home page, http://localhost:8080 (or https://localhost:8443 if you've already secured your Tomcat server).
  2. Click the Tomcat Administration link on the top left of the page.
  3. Type your administrator user name and password, and then click Login.
  4. Click Data Source under the Resources folder in the left pane.
  5. Click Create a New Data Source.
  6. Type all the appropriate information per Table 1.
  7. Click Save, and then click Commit Changes.
  8. Review the server.xml file for the information you just provided.

Note: You may still need to map the global data source name to the local name used in your Web application. To do that, add the following resource link to the <Context> XML tag in your server.xml file:

<ResourceLink global="jdbc/TestDS" name="ds/TestDS"
	           type="javax.sql.DataSource"/>

When you create a data source using the Tomcat Web Application Manager GUI, it creates it in the global name space for all applications to use. For a specific data source used by your application only, add the resource under the <Context> tags.

It is preferable to create the resource definition and resource reference manually in the server.xml file, because it's the same thing but faster and allows you to manipulate the server configuration directly, thus gaining additional knowledge and experience without having to rely on a console.

The server.xml file contains basic resource configurations under the <Context> tags. Simply clear the comments out in the vi editor by deleting the special character in front of the line (for example, the <!-- and the corresponding --> tags. Then, you can further edit the file to match the values found in the next section.

Create a resource definition

Listing 5 provides basic examples of the definitions you need to update in the server.xml file.

Listing 5. Create the resource definition in the server.xml file
<Context path="/{your Web application's context path}" 
    docBase="{the Web application path where your
 WAR is installed}"
        debug="5" reloadable="true" crossContext="true">

  <Resource name="jdbc/{db name}" auth="Container" type="{database type}"
               maxActive="100" maxIdle="30" maxWait="10000"
               username="{your db user}" password="{your db pwd}" driverClassName=
"{your driver class}"
               url="{your jdbc URL}"/>

</Context>

ie. 
<Context path="/DBTest" docBase="DBTest"
        debug="5" reloadable="true" crossContext="true">

  <Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource"
               maxActive="100" maxIdle="30" maxWait="10000"
               username="dbuser" password="test1234" \
			   driverClassName="com.mysql.jdbc.Driver"
               url="jdbc:mysql://localhost/javatest?autoReconnect=true"/>
</Context>

You can define the resource inside the <DefaultContext> tag to be available to all Web applications, or you can define it inside the <Context> element for a specific application.

Create a resource reference

Type vi APP_HOME/WEB-INF/web.xml to create a new web.xml file from the command line. Then, type i to insert the code in Listing 6 with a test data source named TestDB.

Listing 6. Create a WEB-INF/web.xml for this test application
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
        http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
    version="2.4">
  <description>Test SQL for test App</description>
  <resource-ref>
      <description>DB Connection</description>
      <res-ref-name>jdbc/TestDB</res-ref-name>
      <res-type>javax.sql.DataSource</res-type>
      <res-auth>Container</res-auth>
  </resource-ref>
</web-app>

Then, type :wq! to save the file and quite vi. Or, instead of creating the web.xml file from scratch, you can simply update your existing web.xml file. The differences are minor and outlined in Listing 7. The two methods are similar and simply reference your database resources as discussed above.

On the command line, open your existing web.xml file in vi. Then, type i to insert the code in Listing 7 between the <web-app> tags.

Listing 7. Define the resource reference in an existing web.xml file
<description>DB Connection</description>
  <resource-ref>
      <description>DB Connection</description>
      <res-ref-name>jdbc/TestDB</res-ref-name>
      <res-type>javax.sql.DataSource</res-type>
      <res-auth>Container</res-auth>
  </resource-ref>
</web-app>

Type :wq! to save the file and quite vi.

The only difference between the code in Listing 6 and the code in Listing 7 is the <web-app> tag with reference to the schema URLs.

Modify your code with the JNDI references

As a best practice, it's important to note that it's easier for deploying and managing installation releases if you separate the hard-coded database-access references into objects that don't affect the rest of the code. This goes for business logic versus the presentation layer, and so on.

This tutorial doesn't cover creating custom resource factories, using data access objects, or using non-DBCP connections. However, links to more information are provided in Resources.


Security

Securing your Tomcat server is critical if you are ever to serve live Web applications. Even if you only run your Tomcat server as a test server, the following concepts are important to understand and implement.

Server security

Think about security from two different perspectives: server security and application security. Server security includes the Java Security Manager, starting Tomcat under a secure port, and setting up SSL certificates for the server. Application security relates mainly to authentication and authorization of users based on security roles, depending on the protected asset they're trying to access.

SSL setup on the Tomcat server is highly recommended if you're using the server as a stand-alone server. If you have a front-end HTTP server, that server will likely be handling all SSL over HTTP (HTTPS) connections in which SSL is required and routing those requests to the appropriate Tomcat server. In other circumstances, Tomcat servers may need SSL turned on even if they are behind the same firewall in the same network to initiate trusted connections between themselves.

Set up SSL using keytool

SSL connectivity is in essence two servers that trust each other communicating with each other. The way they trust each other is by having security keys that are either self-signed or verified by a third party.

Self-signed certificates are fine for encryption but not acceptable for true online trusted authentication. You will see many warning messages in your browser when attempting to access a site with only a self-signed certificate.

The process for storing, requesting, and importing signed server certificates is discussed below. This information is a prerequisite to performing even the most basic Tomcat security maneuvers, like starting the server under a secure port.

Fortunately, Java provides a relatively simple command-line tool called keytool that can easily create a self-signed certificate. Self-signed certificates are simply user-generated certificates that have not been officially registered with any well-known certification authority (CA) and are therefore not really guaranteed to be authentic at all. However, with keytool, you can generate a certificate request that can be sent to a third party for trusted verification and sent back "signed" so that you can again use keytool to import that signed server certificate. Then, when clients or other servers access your server or application, they will know your server is who it says it is.

Create a keystore

Before you obtain your security certificates, you must have a place to put them. This place is called your keystore. You can also create your self-signed certificate at the same time using the command shown in Listing 8 or Listing 9, depending on your Java version.

Listing 8. Create your keystore and self-signed certificate for Java version 1.6 or later
keytool -genkeypair -alias tomcat -keyalg RSA -keystore /
$CATALINA_HOME/ssl/keystore
Listing 9. Create your keystore and self-signed certificate for Java versions earlier than 1.6
<!-- For Java versions earlier than 1.6, you must run two separate commands. -->
keytool -genkey -alias tomcat -keyalg RSA -keystore /
$CATALINA_HOME/ssl/keystore

<!-- and -->
keytool -selfcert -alias tomcat -keystore /
$CATALINA_HOME/ssl/keystore

You can specify key size, validity, e-mail address, and so on from the command line when creating the key, or you can type each value as you are prompted. Specify a password value of changeit, which is the default password recommended by most documentation. Feel free to set this to something different, if you'd like.

Note: $CATALINA_HOME/ssl is a directory that I created and recommend creating to hold your keystore and server certificates. However, you can include any directory path here as long as you stay consistent when referencing it in the future.

Save typing time

To avoid typing the full $JAVA_HOME/bin/keytool path before each command, add $JAVA_HOME/bin to your PATH variable, if you haven't done so already. Also, in case you were wondering, if you don't specify a -keystore value, keytool still creates the keystore under your user home directory under the name .keystore.

Edit your keystore

You can edit your keystore at a later time, if needed. When you're prompted to type your key password for <tomcat> or whatever your alias name is, press Enter to leave this the same as your keystore password. You will use your alias to reference your keystore from here on out.

Listing 10 shows the code for editing your keystore

Listing 10. Edit your keystore
keytool -genkey -alias tomcat -keyalg RSA  -keystore /
$CATALINA_HOME/ssl/keystore

Change the company, location, default password information, and so on as appropriate.

Obtain a certificate from a trusted authority

To obtain a certificate from the CA of your choice, you must first create a Certificate Signing Request (CSR). This is synonymous with Server Cert Request, if you're familiar with that term from working on other software platforms. Listing 11 shows the code for creating a CSR.

Listing 11. Create your CSR
$keytool -certreq -keyalg RSA -alias tomcat -file certreq.csr /
    -keystore $CATALINA_HOME/ssl/keystore

Now you have a file called certreq.csr that you can submit to the CA. In return, you get a certificate. For a list of third-party digital CAs, see Resources.

To complete the certificate process, perform the following steps:

  1. Go to your third-party vendor's Web site, and obtain the Root certificate or certificate chain.

    Note that some secure servers require an intermediary and Root certificate. You must obtain both from the third-party vendor, both of which will be in the chain. You can also import these certificates individually.

  2. Import the chain by typing:
    keytool -import -alias root -keystore $CATALINA_HOME/ssl/keystore 
        -trustcacerts -file

    where file is the name of the certificate chain.

  3. Import your signed server certificate by typing:
    keytool -import -alias tomcat -keystore $CATALINA_HOME/ssl/keystore -file

    where file is the name of your signed certificate file.

Quick tip

When saving your signed server certificate and certificate chain, you do not have to download and save it. You can actually cut and paste the contents of the SSL RSA key encryption into the file with the appropriate name on the server. You can open chain.csr, select the key contents, and then paste the contents into vi. Save the file by typing :wq!.

You now have the SSL keys necessary to run Tomcat as a trusted server. However, you must now configure Tomcat to use SSL. Tomcat does this through connectors, which the next section defines as you start the server under a secure port.

Start Tomcat under a secure port

By default, the server.xml file contains SSL connector information that you need to "uncomment" to finish configuring Tomcat security. First, make sure the SSLEngine attribute is set to On in the server.xml file—for example:

<Listener className="org.apache.catalina.core.AprLifecycleListener" 
    SSLEngine="on" />

Listing 12 shows the defaults for the Connector element in Tomcat version 6's server.xml file.

Listing 12. Connector element defaults:
<Connector 
           port="8443" minSpareThreads="5" maxSpareThreads="75"
           enableLookups="true" disableUploadTimeout="true" 
           acceptCount="100"  maxThreads="200"
           scheme="https" secure="true" SSLEnabled="true"
           keystoreFile="$CATALINA_HOME/ssl/keystore" keystorePass="changeit"
           clientAuth="false" sslProtocol="TLS"/>
...

Uncomment the <Connector> tag, then set the keystoreFile and keystorePass attributes to match what you configured the keystore for. The default port attribute value used in this example is 8443. This is the TCP/IP port number on which Tomcat will listen for secure connections. You can change this value to any port number you wish. Best practice, however, is to stick to somewhat typical SSL ports, such as 443.

Note that if you change the port number here, you should also change the value specified for the redirectPort attribute on the non-SSL connector. This allows Tomcat to automatically redirect users who attempt to access a secure page or resource specifying that SSL is required.

To access your new protected and secure Tomcat server default page, type the address https://localhost:8443 in your Web browser's address bar. You should see a page similar to Figure 2.

Figure 2. The Security console Welcome page
Tomcat secure 8443

A final nugget of truth to keep in your head for later is, if and when you run secure virtual hosts, you need to add an SSL Factory element to the SSL connector for each server's keystore.

Security manager

The built-in Java Security Manager for Tomcat is simply an alternative to protect your Tomcat server from mischievous or accidental code packages that can cause damage to your server. The JRE lets you purposely restrict certain pieces of code from administering the JVM, having certain permissions on your server file systems, and so on. In many cases, a server hosted in an environment easily accessible from the Web should add this additional layer of security so that hackers cannot manipulate the server or view any files on it. Note, however, that this addition can also be too restrictive if your code needs to write files to your server file system for some reason, so use it wisely and test full application functionality before implementing it in a production environment.

The security policies that Security Manager implements are configured in the $CATALINA_HOME/conf/catalina.policy file, with the appropriate permissions pertaining to different pieces of the Web application. Please review the file to determine what and where you will need to edit to change anything that deviates from the default values.

To start the server with Security Manager policies enabled, type the following command:

$CATALINA_HOME/bin/catalina.sh start -security

Authentication and security roles

Securing the server with SSL keys to make it trusted is great, but now you need to make your application (or at least parts of it) prompt users to securely authenticate to gain access to protected resources. Tomcat provides four common authentication mechanisms and also allows for customized secure authentication. For time purposes, I show you how to set up Basic authentication, and then how to expand this to Form-based, Custom, and Digest authentication.

If you configure Basic authentication, users are prompted with a login dialog box when they attempt to access a protected resource. If you use Form-based authentication, users are redirected to an HTML page that allows them to log in when they attempt to access a protected resource. You use Custom authentication when you require additional information from the user before allowing him or her to log in. And you use Digest authentication when you need an added level of security through hashed passwords.

Basic authentication

First, define the apps-appname.xml file to specify the application that's going to use Basic authentication as well as the users file that it will reference specifically for security roles for this application. Listing 13 shows the contents of this XML file.

Listing 13. Contents of a conf/apps-appname.xml file
<?xml version="1.0" encoding="ISO-8859-1"?>
<webapps>
    <Context path="/sample" docBase="webapps/sample" reloadable="true"> 
            <SimpleRealm filename="conf/users/appname-users.xml" />
    </Context>
</webapps>

Next, you must create the application-specific security role in the appname-users.xml file. Type any user name and password you would like, and make sure you give them the appropriate authentication role. For more information on the available roles, refer to the Tomcat documentation (see Resources).

Listing 14 shows an example appname-users.xml file.

Listing 14. Sample conf/users/appname-users.xml
<tomcat-users>
  <user name="username" password="passwd" roles="rolename" />
</tomcat-users>

Finally, type the details shown in Listing 15 in the main WEB-INF/web.xml file. These details specify your different protected resources and which HTTP methods they are protected against. If you have resources other than JSP or HTML files that you need to protect, you can add them here. Additionally, you will see Basic authentication defined along with which role is given by default to any user on the system.

Listing 15. Sample webapps/appname/WEB-INF/web.xml file
  <security-constraint>
    <web-resource-collection>
      <web-resource-name>user-resource</web-resource-name>
      <description>pages which require login</description>
      <url-pattern>*.jsp</url-pattern>
      <url-pattern>*.html</url-pattern>
      <http-method>GET</http-method>
      <http-method>POST</http-method>
    </web-resource-collection>
    <auth-constraint>
      <description>Must authenticate before querying the system</description>
      <role-name>rolename</role-name>
    </auth-constraint>
    <user-data-constraint>
      <transport-guarantee>NONE</transport-guarantee>
    </user-data-constraint>
  </security-constraint>

  <login-config>
    <auth-method>BASIC</auth-method>
   <realm-name>default</realm-name>
  </login-config>

  <security-role>
    <description>Any user of the system</description>
    <role-name>rolename</role-name>
  </security-role>

Note that you will have to ensure that the <role-name> section points to the roles in which you created the users.

Form-based authentication

Form-based authentication is probably the most common way to authenticate users to access-protected Web pages. It has been around for quite a while and allows you to create custom login and error pages to match the look and feel of your site while building upon the security features of Basic authentication.

Form-based authentication when switching back and forth between HTTPS and HTTP is better than Basic authentication, as your user name and password are not sent with each request. Remember that it is still highly recommended that you use a secure transport mechanism such as HTTPS when using Form-based or any of the four authentication mechanisms mentioned here.

To build on the Basic authentication that you've already set up, perform the following steps:

  1. Create a custom error and login.jsp file (not covered in this tutorial).
  2. Replace the login-config section of the Basic authentication code with the code in Listing 16.
    Listing 16. Modify the Basic authentication code
    <login-config>
       <auth-method>FORM</auth-method>
      <realm-name>Web Demo</realm-name>
       <form-login-config>
          <form-login-page>/admin/login.jsp</form-login-page>
          <form-error-page>/admin/error.jsp</form-error-page>
       </form-login-config>
    </login-config>

    The security constraint information stays the same.

    Note: When creating the HTML form, the following syntax is required:

    <form method="POST" action="j_security_check">
       <input type="text" name="j_username">
       <input type="text" name="j_password">
       <input type="submit" value="Log in">
    </form>
  3. Restart Tomcat for the changes to take effect.

Custom authentication

Both Form-based and Custom authentication concepts are beyond the scope of this tutorial and require additional development. Custom authentication would have you protect a resource—for example, a JSP file—then refer to that resource in the Web-INF directory, as shown in Listing 17.

Listing 17. Referring to a resource in the WEB-INF/web.xml file
 <web-app> 
   <security-constraint>  
    <!-- web resources that are protected --> 
  <web-resource-collection> 
      <web-resource-name>A Protected Page</web-resource-name> 
     <url-pattern>/protected-page.jsp</url-pattern> 
    </web-resource-collection> 

    <auth-constraint> 
      <role-name>resin-user</role-name> 
    </auth-constraint> 
   </security-constraint>

   <login-config> 
    <auth-method>BASIC</auth-method> 
    <realm-name>Basic Authentication Example</realm-name> 
 		<!-- The authenticator tag is Resin-specific --> 
 		<authenticator id='beans.SimpleAuthenticator'/> 
   </login-config>
 </web-app>

Digest authentication

Digest authentication is essentially the same as Basic authentication, except that Digest authentication transmits a password's hash value, not the password itself. Listing 18 shows the update you would make to the web.xml file originally edited for Basic authentication.

Listing 18. The web.xml file edited for Digest authentication
    <auth-method>DIGEST</auth-method>  
    <realm-name>Digest Authentication Example</realm-name> 
   </login-config>  
</web-app>

The only difference between Basic and Digest authentication is the specification of the authentication method, as shown in Listing 18. So, why would you prefer Basic over Digest? I haven't found a great answer for that. Digest is simply the more secure alternative.


Expandability

Expandability is an extremely important concept for anyone wanting to really get into production-type architecture and high availability. It allows you to run many more Web sites or applications in your Web server environment with greater availability than ever before. Of course, such advantages always come at a price. A true architectural solution for what your business needs are should be decided by your management and an IT architect. However, I'm always a fan of techies with extra hardware and too much time on their hands, so if you'd like to explore the concepts below on your own servers, I certainly encourage that!

Virtual hosts

Virtual hosting is simply the concept of allowing one server instance configured on one or more physical server nodes to host two or more applications at the same time. This is an extremely common practice on the Web, mainly because most individuals and small companies cannot afford their own dedicated servers to host their Web applications. With shared space and processes along with ever-improving virtual server software, this is relatively easy for a Web administrator to set up.

Virtual hosting has its obvious limitations, like one application or Web site being codependent on resources with another. What if one application brings a whole server down, which (surprisingly) happens quite often? All other applications are affected. The only true way to remove (or come close to it) such dependencies is to try to eliminate single points of failure in your server environment. That's where clustering comes in.

To use virtual hosts in Tomcat, you just need to set up the Domain Name System (DNS) or hosts data for the host. (For testing, making an IP alias for localhost is sufficient.)

Then, you must add the lines in Listing 19 to the server.xml configuration file.

Listing 19. Set up DNS for the host
    <Engine name="Catalina" defaultHost="localhost" debug="0">
      <!-- This host is the default host. -->
      <Host name="localhost" debug="0" appBase="webapps"
	      unpackWARs="true" autoDeploy="true">
        <Context path="" docBase="ROOT" debug="0"/>
        </Context>
      </Host>

     <!-- This host is the first virtual host: www.example.com. -->
      <Host name="www.example.com" appBase="/home/example/webapp">
        <Context path="" docBase="."/>
      </Host>

    </Engine>

Tomcat's server.xml file, as distributed, contains only one virtual host, but it's easy to add support for additional virtual hosts. The simplified version of the server.xml file in Listing 19 shows the overall additional structure needed to add one virtual host. Each Host element must have one or more Context elements within it; one of these must be the default context for this host, which is specified by having its relative path set to the empty string (for example, path="").

Note: If you've configured Tomcat to support multiple virtual hosts (Web sites), you need to configure a manager for each.

A default Tomcat installation includes the manager. To add an instance of the manager Web application context to a new host, install the manager.xml context configuration file in the $CATALINA_HOME/conf/enginename/hostname folder, as shown in Listing 20.

Listing 20. Example manager context path
<Context path="/manager" debug="0" privileged="true"
         docBase="/opt/tomcat/localhost/webapps/manager">
</Context>

Clustering

Clustering is the second important concept of expandability that you should understand in a Web server environment. In contrast to virtual hosting, which allows you to serve multiple applications from a single server instance, clustering allows you to run multiple server instances from different physical servers while providing robust session and load management. In any true production environment, this is a must. Its purposes are three-fold:

  • It removes single points of failure in the environment from a software or hardware level. Two servers installed on one physical node provide what's called vertical scaling to failover at a software level. However, this does not suffice if there were a hardware failure. Horizontal scaling provides physical and logical failover, as is the case with true clustering.
  • Clustering has the potential to improve performance. Certainly, if your application has its own stand-alone server mansion to exhaust all the resources by its lonesome, then this doesn't hold true. However, most applications share one server with many other applications. When you add more servers and more resources—memory, CPU, and so on—you get increased performance.
  • Clustering is transparent to users. Even if a server goes down in the middle of a user's transaction, session persistence handled through a persistent session database will hold the session data and immediately transfer it to the other server.

Considering how extensive a topic clustering is, this tutorial doesn't get into its implementation. If you truly are hosting many applications or plan to from your Tomcat servers, see Resources for more information.


Additional administration tips

This section outlines a few tasks that you may need to perform as you navigate your server, stop and start processes, troubleshoot, and so on. You can employ these tips could before, after, or during the steps for securing your server or setting up your database.

Granting access to the Tomcat Web Server Administration tool

The Tomcat Web Server Administration tool allows you to see server information, edit connections, modify resources, and more. It also gives you a nice interface in which to manage, create, and change user names and passwords for your main Tomcat admin user as well as add new roles and new users.

This tool is defined in $CATALINA_HOME/webapps/admin.xml. The initial login administrative user must be defined in the same tomcat-users.xml file in which your Tomcat Web Server Administration tool role and user is set up. First, add these two lines between the two <tomcat-users> tags:

cd $CATALINA_HOME/conf
vi tomcat-users.xml

Then, add the code in Listing 21 to the tomcat-users.xml file to grant access to Tomcat Web Application Manager by adding users and roles.

Listing 21. Grant access to the Tomcat Web Server Administration tool
<tomcat-users>
<role rolename="admin"/>
<user username="admin" password="s3cur3" roles="admin"/></user>
</tomcat-users>

You must restart Tomcat to access the Tomcat Web Server Administration tool using the http://localhost:8080/admin URL. To restart the server, use the code in Listing 22.

Listing 22. Restart your Tomcat Server
cd $CATALINA_HOME/bin
./shutdown.sh 
./startup.sh ;tail -f ../logs/catalina.out

You should see something similar to this when you tail your catalina.out log file:

May 15, 2008 4:08:12 PM org.apache.jk.server.JkMain start
INFO: Jk running ID=0 time=0/74  config=null
May 15, 2008 4:08:12 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 6271 ms

Type the URL http://localhost:8080/admin in your Web browser's address bar. If your changes were successful, you'll see the page shown in Figure 3..

Figure 3. Tomcat Web Server Administration tool login page
Tomcat Web Server Administration tool login page

Run the server under a non-root user ID

If you have a true multi-user system with many people logging in and out of your Web server, consider running your Tomcat installation under a Tomcat user that has specific access to your directories and processes. Also, if you have multiple software installations on that server, such as a database installation or a down-version or alternative Web or application server, you need a way to differentiate them. The best way to administer them using a specific ID for each installation. It's definitely good practice in a production environment and something you will typically find when you have segregated administration and deployment teams administering the same server. The administrators are typically given greater control and grant only certain accesses to deployment teams.

First, you must create your user ID and group. If you worked through the previous Tomcat tutorial, you will already have done this. Simply run the following commands:

  • To create a group for Tomcat to run under, use the following code:
    /usr/sbin/groupadd -g {specific gid. Leave this blank, and the operating system will
        assign you a gid}
    {group name}
    ie.
    /usr/sbin/groupadd -g 10004 tomcatgroup
  • To create a unique user for Tomcat to run under, use the following code:
    /usr/sbin/useradd -d {user home directory} -g {user 
    primary group} -u 
    {specific UID. You can leave this blank, and the operating system will 
    assign you a UID.) 
    -s {default shell path for this user} -c "{Description of 
    the user}" {username}
    ie. 
    /usr/sbin/useradd -d /export/home/tomcat -g tomcatgroup -u 
    10010 -s /bin/ksh -c 
    "Main Tomcat Administrative User" tomcat

To change ownership of all $CATALINA_HOME directories to the Tomcat user and Tomcat group, type:

Chown -R tomcat:tomcat $CATALINA_HOME

Note: The -R option specifies a fully recursive change of ownership.

Next, start Tomcat using the jsvc daemon but with the -user option specified. You can do this by directly editing the $CATALINA_HOME/bin/jsvc/native/tomcat.sh script and changing the following parameter to your ID:

TOMCAT_USER=tomcat

Note: You'll find the above variable grouped with other variables such as $JAVA_HOME, $CATALINA_HOME just under the comment section of the script. Use vi or your editor of choice to change that.

You can also make this change by running the jsvc service manually while specifying the -user option:

Cd $DAEMON_HOME (where this is the location of your jsvc-src dir)
Bash#./jsvc -user tomcat -cp ./bin/bootstrap.jar \
-outfile ./logs/catalina.out -errfile ./logs/catalina.err \
        org.apache.catalina.startup.Bootstrap

This is assuming that JAVA_HOME and CATALINA_HOME are already specified. If not, you can add those directories to the above manual startup:

Bash#./jsvc -user tomcat -home /usr/jdk/instances/jdk1.5.0 \
-Dcatalina.home=/opt/apache-tomcat-6.0.16 \
-cp ./bin/bootstrap.jar -outfile ./logs/catalina.out \
-errfile ./logs/catalina.err \
        org.apache.catalina.startup.Bootstrap

Both methods technically start as root and change the user running this process to the user specified.

Determining whether Tomcat is running

Tomcat has no status. So, to determine whether Tomcat is running, you must type:

ps -ef |grep java |grep server

You should see output similar to Listing 23 if you started as the root user with the default startup.sh script.

Listing 23. Output from starting Tomcat as the root user
bash-3.00# ps -ef | grep java|grep server
noaccess   720     1   0 16:35:05 ?           5:06 /usr/java/bin/java -server 
-Xmx128m -XX:+BackgroundCompilation -XX:PermSize=32m

If you started the server using the jsvc daemon manually or Tomcat started upon server startup through the tomcat.sh script under $CATALINA_HOME/bin/jsvc/native/tomcat.sh, you can check to see if the server is running by checking for the existence of the Tomcat .pid file:

Ls -l var/run/tomcat.pid

or by viewing or use Cat on the pid file:

Cat /var/run/tomcat.pid

Check for the .pid file, then use grep on the pid process to see if it's running:

Ps -ef | grep {pid}

Altering the JVM settings

This tip is in particular reference to JVM-allowable memory. The main reason why you would need to raise this value is if you have a large application, plan to use the Tomcat server in a production environment, or plan to run certain controlled load tests against your application with various JVM memory levels to see where memory heap exhaustion takes place. Usually, when running controlled tests, you will set the minimum and maximum heap at the same size until you reach your peak load and gain your desired data. Then, you can change the settings back to normal.

The Tomcat default is set to a maximum of 128MB. To see the value, the line server -Xmx128m appears when you use the status check command. If you're running multiple JVMs, remember not to set the accumulate total of the maximum JVM heap sizes greater than the available memory on your server.

In this case, you can edit the tomcat.sh script or run the jsvc daemon manually with the following options included in the startup line:

server -Xms128m -Xmx512m

Use the command shown in Listing 24 to configure your JVM settings.

Listing 24. Configure your JVM settings
#./jsvc -user tomcat -home /usr/jdk/instances/jdk1.5.0 \
-Dcatalina.home=/opt/apache-tomcat-6.0.16 \
-cp ./bin/bootstrap.jar -outfile ./logs/catalina.out \
-errfile ./logs/catalina.err \
-server -Xms128m -Xmx512m \
        org.apache.catalina.startup.Bootstrap

Typical advanced application server best practices state that it's best to set the minimum JVM heap size to one-quarter of the maximum. Try to avoid changing the memory settings arbitrarily, especially when trying to fix a problem that likely isn't related to the JVM memory in the first place. Increasing the maximum heap size has pros and cons: It's important to understand both.

When your JVM is tuned correctly, 99% of the time, garbage collection (GC) will take less than one second. The remainder will only take a few seconds. Rarely should a GC process take more than 10 seconds.


Summary

Tutorial conclusion and summary

Your intense Tomcat training session is complete! You will likely not need to implement everything discussed in this tutorial at once, but you now have the knowledge to configure a robust Web or application server.

You should be able to deploy your new applications seamlessly from here on out and have a stable and secure Web server that you can use in a test or production environment. Good luck!

Resources

Learn

Get products and technologies

  • Download and find information about J2SE.

Discuss

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into AIX and Unix on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=AIX and UNIX
ArticleID=338831
ArticleTitle=Expand the capabilities of your Tomcat Web server
publish-date=09162008