In the first post of my Tomcat series, Apache Tomcat (1): Core Components and Their Interactions, I tackled the essentials of Apache Tomcat: its open-source nature, and key components like Coyote, Catalina, and Jasper, explaining how these elements work together to support Java web applications. It was a dive into the basics for those of us in DevOps seeking a clearer understanding of what Tomcat does and why it’s a critical tool in web server management.
Building on that foundation, this post focuses on the practical aspects of setting up Tomcat. We’ll briefly cover the installation process and equip you with the knowledge to effectively configure Tomcat, from understanding its directory structure to mastering its key configuration files.
Step 1: Installing Tomcat on a Virtual Machine
Deploying Tomcat on a virtual machine (VM) can offer flexibility and scalability. Here’s a simplified overview:
- Choose Your VM Platform: Whether it’s VMware, VirtualBox, or a cloud-based VM like AWS EC2 or Google Compute Engine, the first step is selecting your platform.
- Setup and Configuration: After setting up your VM with a preferred operating system (Linux, Windows), ensure Java is installed since Tomcat is a Java servlet container.
- Download and Install Tomcat: Navigate to the official Tomcat website, download the appropriate Tomcat version, and follow the installation instructions for your OS.
Or following my step-by-step guides on installing Apache Tomcat in various virtualized environments :
- Enhancing Development Environments: VirtualBox, Vagrant, and Docker
- How to Set Up Apache Tomcat on a Virtual Machine Using Hyper-V on Windows 11 Pro
Step 2: Understanding the Tomcat File System
With Tomcat installed — be it directly on a virtual machine or within a Docker container — we’re ready to explore the home directory of Tomcat, which is the operational hub for managing our applications. This critical directory is typically located at /usr/local/tomcat
.
Let’s navigate to the Tomcat home directory and list its contents:
cd /usr/local/tomcat
ls -l
Here’s an overview of the directory structure:
/usr/local/tomcat
├── bin
│ ├── bootstrap.jar
│ ├── catalina.sh
│ ├── ...
│ ├── shutdown.sh # Script for gracefully shutting down Tomcat
│ └── startup.sh # Script for starting up Tomcat
├── BUILDING.txt
├── conf
│ ├── Catalina
│ │ └── localhost
│ │ └── context.xml # Context configuration for the default web application
│ ├── catalina.policy # Security policy configuration
│ ├── catalina.properties # Main configuration file for Tomcat server settings
│ ├── context.xml # Default context configuration
│ ├── server.xml # Main configuration file for the Tomcat server
│ ├── tomcat-users.xml # User authentication and authorization configuration
│ ├── web.xml # Default deployment descriptor for web applications
│ └── ... # Other configuration files
├── CONTRIBUTING.md
├── lib
│ ├── annotations-api.jar
│ ├── catalina-ant.jar
│ ├── ...
│ └── websocket-api.jar
├── LICENSE
├── logs
│ ├── catalina.2024-03-15.log # Tomcat server log
│ ├── ...
│ └── manager.2024-03-15.log # Manager application log
├── native-jni-lib
│ ├── libtcnative-1.a
│ ├── ...
│ └── libtcnative-1.so.0.3.0
├── NOTICE
├── README.md
├── RELEASE-NOTES
├── RUNNING.txt
├── temp
│ └── safeToDelete.tmp
├── webapps
│ ├── ... # Web applications deployed in Tomcat
│ └── ROOT # Default web application
│ ├── index.jsp
│ ├── ...
│ └── WEB-INF
│ └── web.xml # Deployment descriptor for the default web application
└── work # Temporary working directory used by Tomcat
└── webapps.dist # Web applications distribution directory
├── docs # Documentation for Tomcat and its components
│ ├── aio.html
│ ├── ...
├── examples # Example web applications provided by Tomcat
│ ├── index.html
│ ├── ...
├── host-manager # Host manager web application
│ ├── css
│ ├── images
│ ├── index.jsp
│ ├── META-INF # Meta information directory
└── manager # Manager web application
├── css
├── images
├── index.jsp
├── META-INF # Meta information directory
├── status.xsd
└── WEB-INF
Key Directories
tomcat/
├── bin/
├── conf/
├── lib/
├── logs/
├── native-jni-lib
├── webapps/
├── webapps.dist/
├── work/
└── temp/
- bin: This is where executable files and scripts for managing Tomcat are stored. For example:
-catalina.sh
: Controls the Tomcat server.
-startup.sh
andshutdown.sh
: Start and stop Tomcat, respectively. - conf: Contains crucial configuration files for Tomcat:
-server.xml
: Configures the server.
-web.xml
: Defines settings for web applications.
-tomcat-users.xml
: Manages user authentication. - lib: Tomcat’s libraries are stored here, including JAR files required for Tomcat’s core functionality and various APIs.
- logs: Tomcat logs its activities in this directory, with files like
catalina.yyyy-mm-dd.log
containing server logs and others for specific applications likemanager.2024-03-15.log
for the Manager application. - native-jni-lib: This directory contains native libraries used by Tomcat, like
libtcnative-1.so
, which provides support for native components like OpenSSL. - temp: Temporary files used by Tomcat are stored here.
- webapps: This directory houses web applications deployed in Tomcat. The
ROOT
directory contains the default web application, and additional applications can be added here. - work: Tomcat uses this directory for temporary working files generated during application execution.
- webapps.dist: This directory contains example web applications provided by Tomcat for demonstration and testing purposes. It includes directories like
docs
,examples
,host-manager
, andmanager
. META-INF
andWEB-INF
: Special directories in a Java web application:
- WEB-INF (insidewebapps
): Configuration files and resources specific to each web application. It's not accessible to clients and holds sensitive information likeweb.xml
.
- META-INF (inside JAR or WAR files): Similar toWEB-INF
, but contains metadata files specific to packaged applications or libraries. It's not directly accessible to clients either.
Step 3: Configuration Files and Their Purposes
server.xml
The main configuration file for Tomcat, responsible for defining server-wide settings such as server ports, connectors, and global resources.
<!-- /usr/local/tomcat/conf/server.xml -->
<Server port="8005" shutdown="SHUTDOWN">
<!-- Define a global Executor -->
<Executor name="tomcatThreadPool" namePrefix="catalina-exec-" maxThreads="150" minSpareThreads="4"/>
<!-- Define a global HTTP Connector -->
<Connector executor="tomcatThreadPool" port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
<!-- Define a global HTTPS Connector -->
<Connector port="8443" protocol="HTTP/1.1"
maxThreads="150"
scheme="https" secure="true" SSLEnabled="true"
keystoreFile="conf/keystore.jks" keystorePass="changeit"
clientAuth="false" sslProtocol="TLS" />
<!-- Define a non-SSL AJP Connector -->
<Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />
<!-- Define the Catalina Engine -->
<Engine name="Catalina" defaultHost="localhost">
<!-- Define a Valve for access logging -->
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
prefix="localhost_access_log" suffix=".txt"
pattern="%h %l %u %t "%r" %s %b" />
<!-- Define a virtual host -->
<Host name="localhost" appBase="webapps"
unpackWARs="true" autoDeploy="true">
<!-- Define a Context for the "ROOT" web application -->
<Context path="" docBase="ROOT" debug="0" reloadable="true"/>
<!-- Define additional web applications -->
<!-- Example: -->
<!--
<Context path="/myapp" docBase="myapp" debug="0" reloadable="true"/>
-->
</Host>
</Engine>
</Server>
This is the main configuration file for Tomcat. Key elements include:
<Executor>
: Manage thread pools, which are crucial for efficiently handling incoming requests. Thread pools are used to process tasks concurrently, ensuring optimal utilization of server resources.<Connector>
: Configures how Tomcat listens for incoming connections. Important attributes includeport
,protocol
,maxThreads
, and SSL/TLS settings.<Engine>
: This is the highest level of container in Tomcat, responsible for processing requests. Within an<Engine>
, you can define<Host>
elements for virtual hosting.<Host>
: Represents a virtual host within Tomcat, allowing you to serve multiple domains from a single instance.<Context>
: Defines a web application within Tomcat. While it’s common to define contexts inserver.xml
, it’s recommended to place them in individual XML files under theconf/Catalina/localhost
directory for easier management.<Valve>
: A Valve is a component that sits in the request processing pipeline and can perform various tasks, such as logging, authentication, authorization, and request filtering. Valves are pluggable components that provide a way to intercept and manipulate requests and responses as they flow through the server.
web.xml
Known as the deployment descriptor, it resides in the WEB-INF
directory of a web application or in the conf
directory for global servlet and filter definitions. It specifies servlets, servlet mappings, welcome files, and session configurations.
<!-- /usr/local/tomcat/webapps/myapp/WEB-INF/web.xml -->
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!-- Servlet Configuration -->
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>com.example.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
<!-- Welcome File Configuration -->
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- Session Configuration -->
<session-config>
<session-timeout>30</session-timeout>
<!-- Session tracking mode -->
<tracking-mode>COOKIE</tracking-mode>
</session-config>
<!-- Error Page Configuration -->
<error-page>
<error-code>404</error-code>
<location>/error404.jsp</location>
</error-page>
</web-app>
In this example, the web.xml
file defines various aspects of the web application:
- Servlet Configuration:
- The<servlet>
tag specifies a servlet namedHelloServlet
and its corresponding Java classcom.example.HelloServlet
.
- The<servlet-mapping>
tag maps theHelloServlet
to the URL pattern/hello
, meaning that requests to/hello
will be handled by this servlet. - Welcome File Configuration:
- The<welcome-file-list>
tag defines the list of welcome files that the server should consider when a request is made to the root of the web application. In this case,index.jsp
is specified as the welcome file. - Session Configuration:
The<session-config>
tag sets the session timeout to 30 minutes and specifies the session tracking mode asCOOKIE
. - Error Page Configuration:
- The<error-page>
tag defines how the application should handle HTTP error code 404 (resource not found) by redirecting to the/error404.jsp
page.
The web.xml
file acts as a roadmap for the web application, guiding the server on how to handle requests and manage sessions, thereby ensuring smooth operation and enhanced user experience.
context.xml
context.xml
is used to configure individual web applications deployed on the Tomcat server. It allows you to specify resources, environment variables, and other settings specific to each web application. It can be placed inside an application’s META-INF
directory for app-specific settings or in the conf
directory for global settings.
<!-- /usr/local/tomcat/webapps/myapp/META-INF/context.xml -->
<Context>
<!-- Database Connection Pool -->
<Resource name="jdbc/myDataSource" auth="Container" type="javax.sql.DataSource"
maxTotal="100" maxIdle="30" maxWaitMillis="10000"
username="dbuser" password="dbpass" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/mydatabase"/>
<!-- Enable JNDI -->
<ResourceLink global="jdbc/myDataSource" name="jdbc/myDataSource" type="javax.sql.DataSource"/>
<!-- Environment Variables -->
<Environment name="ENV_VAR_NAME" value="ENV_VAR_VALUE" type="java.lang.String"/>
<!-- Security Constraints -->
<SecurityConstraint>
<web-resource-collection>
<web-resource-name>Restricted Area</web-resource-name>
<url-pattern>/admin/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>admin</role-name>
</auth-constraint>
</SecurityConstraint>
<!-- Session Management -->
<SessionConfig>
<session-timeout>30</session-timeout>
<cookie-config>
<name>MY_SESSION_ID</name>
<http-only>true</http-only>
<secure>true</secure>
</cookie-config>
</SessionConfig>
</Context>
- Database Connection Pool Configuration: This section defines a connection pool named
jdbc/myDataSource
, which provides database connections to the web application. It specifies parameters such as maximum total connections, maximum idle connections, and connection timeout settings. - JNDI Resource Linking: The
<ResourceLink>
element enables the application to access the defined resource (jdbc/myDataSource
) through Java Naming and Directory Interface (JNDI) lookup, promoting resource reuse and encapsulation. - Environment Variables: Developers can set environment variables specific to the application using the
<Environment>
element. This allows for customization and flexibility in configuring the application environment. - Security Constraints: The
<SecurityConstraint>
element allows developers to enforce security restrictions on certain parts of the application. In this example, access to URLs under/admin/*
is restricted to users with theadmin
role. - Session Management Configuration: This section specifies session management settings, such as session timeout duration and cookie configuration. It ensures optimal management of user sessions within the application.
Overall, context.xml
empowers developers to fine-tune the configuration of their web applications, enabling efficient resource utilization, enhanced security, and customized environment settings tailored to the specific needs of each application deployed on the Tomcat server.
tomcat-users.xml
tomcat-users.xml
serves as a user database file where you can define user accounts and their associated roles. Tomcat uses this information for authenticating users attempting to access protected resources on the server.
<!-- /usr/local/tomcat/conf/tomcat-users.xml -->
<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
<user username="admin" password="password" roles="admin, manager-gui"/>
<user username="deployer" password="password" roles="manager-script"/>
<user username="tomcat" password="password" roles="manager-gui, manager-script"/>
</tomcat-users>
- User Definition: Each
<user>
element defines a user account with attributes forusername
,password
, androles
. - Roles: Roles represent predefined sets of permissions that determine the actions a user can perform within Tomcat.
- In the provided example, users are assigned roles such asadmin
,manager-gui
, andmanager-script
.
Different roles provide different levels of access to Tomcat’s management interfaces and resources.
Comparison of XML Configuration Files in Apache Tomcat
Comparison of XML Configuration Files in Apache Tomcat
Configuration File | Scope | Functionality
------------------------------------------------------------------------------
server.xml | Global | Configures Tomcat's server-wide settings such as connectors, thread pools, virtual hosts, and global servlet definitions.
------------------------------------------------------------------------------
context.xml | Application-Specific or Global| Configures resources and environment settings for individual web applications or globally across all web applications.
------------------------------------------------------------------------------
web.xml | Application-Specific | Defines how each web application handles requests and responses, including servlets, filters, welcome files, and error pages.
------------------------------------------------------------------------------
tomcat-users.xml | Global | Defines user accounts and roles for authentication and authorization purposes within Apache Tomcat.