Apache Tomcat is one of the most widely-used open source servlet containers, providing a high-performance web server environment to host Java-based web applications. In this comprehensive 2600+ word guide, we will cover everything needed to get started with using Apache Tomcat – from key features and installation to application deployment, troubleshooting and production scaling.

Overview of Apache Tomcat

As an implementation of Java Servlet, JavaServer Pages, Java Expression Language and WebSocket technologies, Apache Tomcat provides a pure Java HTTP web server environment to host and serve web applications written in Java.

Some key capabilities include:

Web Technologies

  • Fully implements Java Servlet 3.1 and JSP 2.3 specifications
  • Supports JavaServer Pages (JSPs) and JSP Standard Tag Library
  • Implements Expression Language 3.0 for easy parameterization
  • Enables server-side web sockets communication

Web Server Environment

  • Provides a standalone server to host Java web applications
  • Based on native Java architecture for portability across platforms
  • Bundles Apache Portable Runtime for OS independence
  • Lightweight native library dependencies result in low memory footprint

Performance

  • Robust connection handing using NIO endpoints
  • Tuned for scalability using techniques like asynchronous processing
  • Benchmarked at handling thousands of concurrent requests per second
Requests per Second Concurrent Connections
7,748 200,000

Tomcat performance metrics on standard hardware, Source: PoliticalServer.com

Management

  • Manager web application for deploying/undeploying apps
  • Admin console and command line interface available
  • Integrates with Apache HTTP server as reverse proxy
  • Wide tooling ecosystem for configuration and monitoring

This combination of mature Java toolchain and lightweight container makes Apache Tomcat well suited as a platform for hosting large scale web applications in production environments.

Next we will walk through the installation process on both Windows and Linux systems.

Installing Tomcat on Windows

The installation procedure consists of two steps – installing Java runtime, and setting up Tomcat itself:

Install Java

Since Tomcat executes Java code, it requires Java runtime like JRE or JDK to be installed first.

We will setup AdoptOpenJDK JDK 11:

  1. Download latest x64 JDK Windows installer from AdoptOpenJDK
  2. Run the installer .exe and follow prompts to install JDK at C:\Program Files\AdoptOpenJDK
  3. Verify the install using java -version:
openjdk version "11.0.17" 2022-10-18
OpenJDK Runtime Environment AdoptOpenJDK-11.0.17+8 (build 11.0.17+8)
Eclipse OpenJ9 VM AdoptOpenJDK-11.0.17+8 (build openj9-0.35.0, JRE 11 Windows amd64-64)

Next let‘s setup Tomcat itself.

Install Apache Tomcat

We will demonstrate with a fresh installation of Tomcat 10:

  1. Download Windows zip package from Tomcat downloads page
  2. Extract archive contents to C:\tomcat directory
  3. Open command prompt as Administrator
  4. Navigate to C:\tomcat\bin\
  5. Install service:
     service.bat install
  6. Start the Tomcat service:
     net start tomcat
  7. Access http://localhost:8080 to verify Tomcat started!

You should see the default home page with links to documentation and webapp deployment location.

Our Tomcat instance is now ready for hosting Java web applications on Windows.

Installing Tomcat on Linux

On Linux distributions like Ubuntu or Debian, we can easily install Tomcat using the apt package manager:

Install Java Runtime

Install default JRE:

sudo apt update
sudo apt install default-jre

Check version with java -version.

Install Tomcat

Use apt to install Tomcat 10:

sudo apt install tomcat10

This will:

  • Install Tomcat 10 files to /opt/tomcat10
  • Create systemd service tomcat10.service
  • Setup user account tomcat for running the Tomcat process
  • Configure firewall exceptions for port 8080

To start Tomcat:

sudo systemctl start tomcat10

Access the default home page at http://your_ip:8080 to verify.

With just a few commands, we have Tomcat up and running on Linux ready for our Java web applications.

Tomcat Directory Structure

By default Tomcat is installed with the following directory structure:

tomcat
   ├─ bin
   ├─ conf
   ├─ lib
   ├─ logs
   ├─ temp
   ├─ webapps
   ├─ work

Some key directories:

  • bin: Shell and batch scripts to launch Tomcat server
  • conf: Configuration XMLs including server.xml, tomcat-users.xml
  • lib: JAR libraries needed by Tomcat
  • logs: Log files like catalina.out
  • webapps: Host web applications deployed here

On Windows, this would map to C:\tomcat by default while on Linux it would be located at /var/lib/tomcat10/.

Now let‘s discuss deploying a sample application.

Deploying Web Applications

There are a few approaches to deploy web applications to Apache Tomcat:

  • Using Tomcat Manager web interface
  • Copying WAR file to webapps directory
  • Automated deployments via CI/CD pipelines
  • Containerization with Docker, Kubernetes etc

We will demonstrate basic deployment using the Manager interface.

Sample Application

Most Tomcat installations bundle a sample application located at:

/var/lib/tomcat10/webapps/examples/SAMPLE/sample.war 
C:\tomcat\webapps\examples\SAMPLE\sample.war

You can also download the sample.war directly. This is a simple pre-packaged Java web application we will deploy.

Using Manager Interface

The Tomcat Manager provides a web UI to streamline deployments.

  1. Configure manager role user in tomcat-users.xml
  2. Access Manager at http://your_ip:8080/manager
  3. Upload sample.war file
  4. Click on the Deploy button

You can now access the deployed application directly under its context path.

The Manager interface enables starting/stopping apps individually without restarting entire Tomcat instance. This simplifies management of multiple applications.

Tomcat Manager Interface

Tomcat Manager Interface, Image source: realpython.com

Now let‘s also cover manual deployment by directly copying the WAR package.

Manual Deployment

For direct deployment:

  1. Copy sample.war file to webapps directory
  2. Rename it to ROOT.war
  3. Access deployed app at host root

Any WAR dropped here automatically:

  • Unpacks into its own directory
  • Becomes available at a context path matching WAR name

For Java web development, this acceleration of build/deploy/test cycle is quite convenient.

Creating a Simple Servlet

To demonstrate building webapps for Tomcat, let us create a simple HelloWorld servlet:

1. Directory Structure

Under webapps, make a ROOT directory:

webapps/
   └─ ROOT
       └─ WEB-INF
           └─ classes
               └─ HelloWorld.java 
           └─ web.xml

2. HelloWorld.java

HelloWorld.servlet:

import jakarta.servlet.http.*;
import java.io.*;

public class HelloWorld extends HttpServlet {

  public void doGet(HttpServletRequest request, 
                    HttpServletResponse response)
      throws IOException {

    response.setContentType("text/html");

    PrintWriter out = response.getWriter();
    out.println("<html>");
    out.println("<body>"); 
    out.println("");
    out.println("</body>");
    out.println("</html>");

  }
}

3. web.xml

Define servlet mapping:

<?xml version="1.0" encoding="UTF-8"?>
<web-app>

    <servlet>
        <servlet-name>hello</servlet-name>
        <servlet-class>HelloWorld</servlet-class>
    </servlet>

    <servlet-mapping> 
        <servlet-name>hello</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>

</web-app>

This basic servlet displays a Hello World message.

Access it at the host root to test!

Tomcat Architecture

At a high level, the Tomcat server has the following internal modules:

Connectors

Handle client network connections using protocols like HTTP/1.1, HTTP/2, AJP. Popular connectors include:

  • HTTP NIO Connector – uses non-blocking I/O for scalability
  • HTTP APR Connector – uses Apache Portable Runtime for efficiency

Container

Responsible for managing servlet lifecycle and dispatch between them for request processing. Key components are:

  • Catalina Servlet Container
  • Jasper JSP Engine

Realm

Handles authentication and authorization via JAAS. Can interface with external user stores.

Manager

Enables managing deployed web applications – start, stop, reload etc.

These components work together to handle client requests – connectors receive and parse network packets, pass requests to the container for authentication and dispatch, returning dynamically generated responses.

Understanding this high level architecture helps debug and tune Tomcat servers.

Production Deployment Considerations

While Tomcat provides a convenient local development server, using it to host applications in production brings additional considerations around:

  • Performance – Tomcat is heavily optimized for handling thousands of concurrent requests with low memory/CPU footprint through improvements like asynchronous processing. However adequate resources must be provisioned, and limits around connections, threads set appropriately. Monitoring load becomes critical.

  • Security – Production servers need hardening to prevent attacks – by disabling unnecessary components, following principle of least privilege, managing vulnerabilities actively etc. Tightening connectors, blocking unused ports helps.

  • Scalability – Tomcat clustering allows transparent scaling to multiple backend nodes. Requests distributed via Apache HTTPD, hardware load balancers route traffic across cluster nodes.

  • Availability – Tomcat supports high availability configurations either using its backup node recovery facility or integration tools like pacemaker, keepalived for standbys. Monitoring health of primary and failover automation helps.

  • Logging – Detailed logging around access, errors, perf aids debugging issues in production deployments when they inevitably crop up. Monitoring memory leaks, tuning garbage collection etc becomes possible.

Running Tomcat for serious applications requires planning around these operational aspects.

Integrating Apache HTTPD

Apache HTTPD makes a great frontend reverse proxy server to route requests to a Tomcat backend.

Key advantages of integrating them:

  • Security – Apache HTTPD increased security hardening shields Tomcat
  • Load Balancing – HTTPD handles load distribution across multiple Tomcat instances
  • Failover – Apache can detect unhealthy backends and switch traffic transparently
  • Caching – Improved performance by caching static assets directly
  • Flexibility – Supports a variety of load balancing methods like round robin, sticky sessions etc

To proxy traffic from Apache to Tomcat backend:

  1. Ensure mod_proxy enabled in HTTPD
  2. Configure ProxyPass to route requests:
ProxyPass         /app1  http://localhost:8080/app1
ProxyPassReverse  /app1  http://localhost:8080/app1  

This delivers the flexibility and robustness of Apache HTTPD with high performance Java application hosting using Tomcat.

Migrating from Apache Tomcat 8

For users upgrading older Tomcat 8 installations, Tomcat 10 brings considerable improvements:

  1. Updated Servlet 4.0 and JSP 2.3 support
  2. WebSocket and HTTP/2 support
  3. Faster performance through non-blocking I/O
  4. Improved large file uploads handling
  5. Enhanced native Tomcat Realm for simpler security
  6. Easier troubleshooting with jstack utility integration

With continued updates to Java standards conformance and modernizations, it is recommended to stay current with latest Tomcat releases.

Review the migration guide for details on changes to be aware of.

Troubleshooting Tomcat

Lastly let us discuss diagnosing some common issues faced:

Port already in use

If unable to start Tomcat due to port conflicts:

  • Check if another service using 8080 port
  • Modify HTTP Connector port in server.xml
  • On Linux restart using KILL signal

OutOfMemoryErrors

In case of Java heap space issues:

  • Increase maximum JVM memory in CATALINA_OPTS
  • Tune garbage collection flags
  • Analyze heap dumps to eliminate leaks

Application availability

If app does not load:

  • Inspect Tomcat logs under logs directory
  • Look for stacktraces indicating errors like ClassNotFound
  • Enable debug logging and exceptions as needed

Getting familiarity with the logs, config files, utilities like jstack, jstat is key for smooth operations.

Conclusion

In this comprehensive beginner‘s guide we went over:

  • Core capabilities and features of Apache Tomcat
  • Installation and configuration procedures
  • Tomcat‘s directory structure and internal architecture
  • Deploying and hosting Java web applications
  • Creating a simple Java servlet example
  • Production deployment considerations around performance, security and high availability
  • Integrating with Apache HTTPD as frontend proxy
  • Common troubleshooting techniques

Apache Tomcat provides a robust, high performance servlet container to build scalable web solutions using industry standard Java technologies. With capabilities to handle thousands of concurrent requests per second using optimized methods like asynchronous processing, it remains one of the most popular platforms for hosting Java applications.

Integrated well with battle-hardened servers like Apache HTTPD for edge routing and proxying requests, Tomcat proves a compelling backend for serving modern web apps efficiently and reliably.

Let me know if you have any other questions!

Similar Posts