Popular Searches
Popular Course Categories
Popular Courses

Deploying Applications on Tomcat and Container Platforms

Deploying Applications on Tomcat and Container Platforms

Advanced Java Application Testing and Deployment

Deploying Applications on Tomcat and Container Platforms – Detailed Notes

Course: Advance Java Training

Topic: Deploying Applications on Tomcat and Container Platforms

Course Link: Advance Java Training at JustAcademy

Demo Link: Register for a Free Course Demo

Website: JustAcademy Official Website


1. Introduction to Application Deployment

Application deployment is the process of preparing, packaging, configuring, and running a software application in an environment where users or other systems can access it. In Java development, deployment commonly involves building an application, packaging it as a JAR or WAR file, configuring the runtime environment, and publishing it to an application server or container platform.

Apache Tomcat is a widely used Java web server and servlet container. It can run Java web applications that use technologies such as Servlets, JavaServer Pages (JSP), and compatible Spring web applications. Container platforms such as Docker provide isolated, portable environments for running applications with their required runtime dependencies.

Deployment knowledge is important because an application that works on a developer's computer may fail in another environment due to differences in Java versions, environment variables, ports, configuration, file permissions, database access, or dependency versions.

Learning Objectives

  • Understand the purpose of Apache Tomcat and container platforms.
  • Differentiate JAR, WAR, and Docker image packaging.
  • Build and deploy a Java web application to Tomcat.
  • Understand deployment using the Tomcat web application directory and Manager application.
  • Containerize a Java application using Docker.
  • Configure ports, environment variables, external services, and application settings.
  • Diagnose common deployment errors using logs and health checks.
  • Apply security, reliability, and deployment best practices.

2. Understanding Apache Tomcat

Apache Tomcat is an open-source implementation of Java web technologies, including the Servlet and Jakarta Server Pages specifications. It provides the runtime environment required by compatible Java web applications.

2.1 Main Components of Tomcat

Component Description
Catalina The servlet container responsible for managing web applications, servlet lifecycles, and request processing.
Connector Accepts client connections, commonly over HTTP, and passes requests into Tomcat.
Engine Processes requests for virtual hosts.
Host Represents a virtual host that can contain multiple web applications.
Context Represents an individual deployed web application and its configuration.
Webapps Directory The default application deployment directory in a standard Tomcat installation.
Tomcat Manager A web application that can manage deployments when appropriately configured and secured.

2.2 Common Tomcat Directories

Directory Purpose
bin/ Contains startup, shutdown, and other administrative scripts.
conf/ Contains server configuration files, including server.xml and web.xml.
logs/ Stores server and application-related log output, depending on configuration.
webapps/ Default location for deployed web applications and WAR files.
lib/ Contains libraries shared by the Tomcat server.
work/ Stores generated working files, such as compiled JSP artifacts.
temp/ Provides temporary storage for server operations.

3. JAR, WAR, and Container Image

Java applications can be packaged in different formats depending on their architecture and deployment target.

Format Purpose Typical Runtime
JAR Packages Java classes, resources, and dependencies according to the application build configuration. Java runtime; executable Spring Boot JARs can include an embedded server.
WAR Packages a web application for deployment to a compatible servlet container. External servlet container such as Tomcat.
Docker Image Packages an application and its runtime environment into an image used to create containers. Docker Engine or a compatible container runtime.

Important distinction: A traditional Spring application packaged as a WAR can be deployed to a compatible external Tomcat server. A Spring Boot application packaged as an executable JAR usually runs with its embedded server. A Docker image may contain either an executable JAR or a WAR deployed to Tomcat, depending on the selected design.

4. Preparing the Application for Deployment

Before deploying an application, verify that the code builds successfully, its dependencies are available, its configuration is appropriate for the target environment, and its required services can be reached.

4.1 Pre-Deployment Checklist

  • Confirm the required Java version.
  • Check the Tomcat version and Servlet/Jakarta compatibility.
  • Run unit and integration tests.
  • Verify database connection settings and credentials.
  • Externalize environment-specific configuration.
  • Confirm that the required ports are available.
  • Check application logs for startup errors.
  • Prepare a rollback plan for production deployment.

4.2 Build a Maven Project

For a Maven-based Java project, run the following command from the directory containing pom.xml:

mvn clean test package

This command removes previous build output, runs the configured tests, and packages the application. The resulting artifact is commonly located in the target/ directory.

For a WAR project, the artifact may look like:

target/myapp.war

For an executable Spring Boot JAR, it may look like:

target/myapp.jar

The exact file name depends on the project's Maven configuration.

4.3 Configure the Packaging Type

A traditional web application deployed to an external servlet container typically uses WAR packaging.

<packaging>war</packaging>

For Spring Boot applications, follow the framework's deployment requirements. When packaging a Spring Boot application as a WAR for an external servlet container, the application generally needs the appropriate servlet initializer configuration and a compatible servlet API dependency arrangement.

For example, a Spring Boot application may extend SpringBootServletInitializer:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

@SpringBootApplication
public class MyApplication extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(
            SpringApplicationBuilder builder) {
        return builder.sources(MyApplication.class);
    }

    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

This pattern supports deployment to a compatible external servlet container. Check the Spring Boot and Tomcat compatibility requirements before choosing versions.

5. Installing and Starting Apache Tomcat

Download a Tomcat release compatible with the Java version and web technologies used by your application. Extract the distribution into a suitable directory and configure the required environment variables.

5.1 Important Environment Variables

Variable Purpose
JAVA_HOME Points to the Java Development Kit or runtime installation required by the selected Tomcat release.
CATALINA_HOME Identifies the Tomcat installation directory.
CATALINA_BASE Identifies a Tomcat instance's runtime configuration, deployment, and log base. It can differ from CATALINA_HOME.

5.2 Starting Tomcat on Windows

Open Command Prompt, navigate to the Tomcat bin directory, and run:

catalina.bat run

Alternatively, use startup.bat to start Tomcat in a separate process when appropriate for the installation.

5.3 Starting Tomcat on Linux or macOS

cd /path/to/apache-tomcat/bin
chmod +x *.sh
./catalina.sh run

Use the foreground run command during learning and troubleshooting because startup messages are visible in the terminal. For managed environments, use the service or process-management approach configured by the administrator.

5.4 Verify Tomcat

When Tomcat starts successfully and its HTTP connector is configured on port 8080, open the following address:

http://localhost:8080/

The port may differ if the server configuration has been changed or another service uses the default port.

6. Deploying a WAR File to Tomcat

A WAR (Web Application Archive) file contains a web application's resources, classes, and required libraries in a standard structure. Tomcat can deploy the WAR file and make the application available under a context path.

6.1 Deployment Using the Webapps Directory

  1. Build the application and locate the generated WAR file.
  2. Ensure Tomcat is installed and configured correctly.
  3. Copy the WAR file into the configured application base directory, commonly $CATALINA_BASE/webapps/.
  4. Allow Tomcat to deploy the WAR according to its host configuration.
  5. Review startup logs for errors.
  6. Open the application using the appropriate context path.

Example WAR file:

myapp.war

If the file is deployed under the default host's webapps directory, the application is commonly available at:

http://localhost:8080/myapp/

The context path is normally derived from the WAR filename without the .war extension unless deployment configuration specifies otherwise.

6.2 Deployment on Startup and Automatic Deployment

Tomcat can deploy applications during startup. Depending on the host configuration, it can also detect certain application changes while running. Common configuration options include:

  • deployOnStartup — controls deployment of applications during startup.
  • autoDeploy — controls automatic deployment and redeployment while Tomcat is running.
  • unpackWARs — determines whether deployed WAR files are expanded into directories.

Automatic deployment can be useful in development and controlled environments. For production, deployment should follow a deliberate release process with appropriate validation, monitoring, and rollback procedures.

7. Deploying Through the Tomcat Manager

The Tomcat Manager web application can deploy, start, stop, reload, and undeploy applications without requiring a complete server restart. Access and operations depend on the Manager configuration and assigned user roles.

7.1 Manager Configuration

Tomcat Manager access is controlled through configuration and role-based authorization. Create an appropriately restricted account using the configuration supported by your Tomcat version. Do not expose administrative access publicly or use weak credentials.

7.2 Deploying an Application

  1. Start Tomcat.
  2. Open the Manager interface if it is installed and enabled.
  3. Authenticate with an authorized account.
  4. Select the WAR upload or deployment option.
  5. Choose the generated WAR file.
  6. Deploy the application and inspect the result message.
  7. Open the application's context path and test key endpoints.

The text-based Manager interface also supports deployment operations through HTTP requests. Automated deployments should use securely stored credentials and an appropriately restricted Manager account.

7.3 Important Security Considerations

  • Do not grant administrative roles to ordinary application users.
  • Restrict Manager access to trusted networks or approved administrative routes.
  • Use HTTPS when credentials or administrative requests cross untrusted networks.
  • Keep credentials outside source code and version control.
  • Remove unused administrative applications and accounts according to organizational policy.

8. Understanding Context Paths

A context path is the URL prefix used to access a deployed web application. For example, if myapp.war is deployed under the context path /myapp, its URLs may begin with http://localhost:8080/myapp/.

WAR File Typical Context Path Example URL
inventory.war /inventory http://localhost:8080/inventory/
studentportal.war /studentportal http://localhost:8080/studentportal/
ROOT.war / http://localhost:8080/

Actual routing may differ if a custom context configuration, reverse proxy, or application-specific route is used. When testing an API, include both the context path and the endpoint path.

9. Introduction to Container Platforms

A container packages an application process and the files it needs into an isolated runtime environment. Containers use the host operating system's kernel but provide separation for processes, filesystems, and networking. Container images can be built once and run across compatible environments.

Docker is a common platform for building and running containers. Container orchestration platforms can manage larger deployments, including replicas, service discovery, rolling updates, health monitoring, and resource allocation.

9.1 Benefits of Containerization

  • Portability: Consistent application packaging across compatible environments.
  • Isolation: Application processes and filesystem views are separated from other workloads.
  • Reproducibility: A versioned image provides a repeatable deployment artifact.
  • Scalability: Multiple container instances can be launched when the application architecture supports them.
  • Automation: Containers integrate with continuous integration and continuous delivery pipelines.
  • Resource control: Container runtimes and orchestrators can apply CPU and memory limits.

9.2 Virtual Machines and Containers

Feature Virtual Machine Container
Operating system Usually includes a guest operating system. Shares the host kernel.
Packaging Includes virtual hardware configuration and a guest OS environment. Includes application files, dependencies, and image metadata.
Startup Generally starts a full guest OS. Usually starts an application process more quickly.
Isolation model Virtualized hardware boundary. Operating-system-level process and resource isolation.
Common use Full OS workloads and strong environment separation. Portable application packaging and scalable service deployment.

10. Containerizing a Java Application

To containerize a Java application, build the artifact, choose a compatible base image, copy or package the artifact, define the startup command, expose the intended application port, and configure runtime settings.

10.1 Example: Containerizing a Spring Boot JAR

Assume Maven builds the application as target/myapp.jar and the JAR runs on the Java version provided by the selected base image.

FROM eclipse-temurin:21-jre
WORKDIR /app
COPY target/myapp.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]

This is a basic learning example. Choose a maintained, supported base image that matches your project's Java requirements. For production, consider image pinning, vulnerability scanning, a non-root user, a minimal runtime image, and a controlled build pipeline.

10.2 Build the Docker Image

Save the preceding file as Dockerfile in the project root and run:

docker build -t myapp:1.0 .

The command builds an image named myapp with the tag 1.0. Tags help identify releases, but a production pipeline should also track immutable image digests.

10.3 Run the Container

docker run --name myapp-container -p 8080:8080 myapp:1.0

The port mapping publishes container port 8080 on host port 8080. If the application starts successfully, access its configured endpoint through the host address and port.

http://localhost:8080/

For an API, use the actual controller endpoint, such as /api/products, rather than assuming the application serves a page at the root path.

11. Running Tomcat Inside a Docker Container

Another deployment model is to use a Tomcat base image and copy a WAR file into Tomcat's web application directory. This is suitable for compatible applications that require an external Tomcat runtime.

11.1 Example Tomcat Dockerfile

FROM tomcat:10.1-jdk21-temurin
COPY target/myapp.war /usr/local/tomcat/webapps/myapp.war
EXPOSE 8080

Use a maintained image tag that actually exists and matches the Java, Servlet, and Jakarta API requirements of the application. The tag above is illustrative; verify available tags and compatibility before building. The application must be compatible with the selected Tomcat major version.

11.2 Build and Run the Tomcat Image

docker build -t myapp-tomcat:1.0 .
docker run --name myapp-tomcat-container -p 8080:8080 myapp-tomcat:1.0

If the WAR is named myapp.war, the typical context path is /myapp. Confirm the deployment result in the container logs before testing the application.

11.3 Choosing the Right Container Model

Deployment Model Best Fit Key Consideration
Executable Spring Boot JAR Applications designed to use an embedded web server. Run the JAR directly in a Java runtime image.
WAR on external Tomcat Applications designed for a servlet container. Check servlet API and Tomcat version compatibility.
WAR inside a Tomcat container Containerized deployments requiring a Tomcat runtime. Keep the Tomcat image and WAR artifact compatible and patched.

12. Managing Configuration and Environment Variables

Development, testing, staging, and production environments often require different database URLs, API endpoints, feature flags, and credentials. Avoid embedding environment-specific values in source code or container images when they should be configurable at runtime.

12.1 Passing an Environment Variable

docker run --name myapp-container \
  -p 8080:8080 \
  -e SPRING_PROFILES_ACTIVE=prod \
  myapp:1.0

Spring Boot can use environment variables and external configuration files according to its configuration rules. For example, SPRING_PROFILES_ACTIVE selects the active Spring profile.

12.2 External Configuration Principles

  • Keep environment-specific settings outside the application binary when possible.
  • Use separate configuration for development, testing, and production.
  • Store secrets in an approved secrets manager or platform-provided secret mechanism.
  • Never commit production passwords, private keys, or tokens to source control.
  • Document required environment variables and their expected formats.
  • Validate required settings during application startup.

13. Database Connectivity in Containerized Applications

A containerized Java application may connect to a database running on another container, a managed database service, or an external server. The database hostname must be reachable from the application's runtime environment.

13.1 Common Database Deployment Considerations

  • Configure database connection properties through environment-specific settings.
  • Use a supported JDBC driver and compatible database version.
  • Ensure that network rules permit the required connection.
  • Use connection pooling and set sensible pool limits.
  • Handle connection failures and database outages gracefully.
  • Apply database schema migrations through a controlled release process.
  • Keep database credentials in a secure secret store.

Important: Inside a container, localhost normally refers to that same container, not a separate database container. In a Docker network, applications commonly connect using the database service or container name when the network is configured accordingly.

14. Container Networking and Port Mapping

Container networking allows applications and supporting services to communicate. Docker port publishing maps a port on the host to a port inside the container.

docker run -p 9090:8080 myapp:1.0

In this example, host port 9090 forwards to container port 8080. Users can access the service through the host's port 9090, assuming network and firewall rules allow access.

Networking Best Practices

  • Publish only the ports that need to be accessed externally.
  • Use private container networks for internal services.
  • Do not expose database ports publicly without a clear security requirement.
  • Configure firewall rules and reverse proxies appropriately.
  • Use DNS names or service discovery rather than hard-coded container IP addresses.

15. Container Lifecycle Management

Container lifecycle commands are useful for running, inspecting, stopping, restarting, and removing application containers.

Command Purpose
docker ps Lists running containers.
docker ps -a Lists running and stopped containers.
docker logs myapp-container Displays the container's log output.
docker logs -f myapp-container Follows new log output.
docker inspect myapp-container Displays detailed container configuration and runtime state.
docker stop myapp-container Requests the container to stop gracefully.
docker start myapp-container Starts a stopped container.
docker restart myapp-container Restarts a container.
docker rm myapp-container Removes a stopped container.
docker image ls Lists locally available images.

Do not remove containers or volumes without confirming whether they contain data that must be retained. Application containers should generally be replaceable; persistent business data should be stored in managed databases or appropriately configured persistent storage.

16. Health Checks and Application Monitoring

A process that is running does not necessarily mean the application is ready to serve requests. Health checks help determine whether an application has started correctly and whether it can perform its intended role.

16.1 Health Check Types

  • Liveness: Indicates whether the application process is functioning or should be restarted.
  • Readiness: Indicates whether the application is ready to receive traffic.
  • Startup: Gives a slow-starting application time to initialize before regular liveness checks are enforced.

Spring Boot applications can expose health information through Spring Boot Actuator when the dependency and endpoints are configured appropriately. Access should be restricted to approved monitoring systems.

16.2 Example Docker Health Check

HEALTHCHECK --interval=30s --timeout=5s --start-period=40s --retries=3 \
  CMD curl -f http://localhost:8080/actuator/health || exit 1

This is an illustrative example and assumes that the image includes curl and the health endpoint is enabled and accessible. If those assumptions are false, use a suitable probe command or the platform's native health-check configuration. A Docker health status alone does not automatically restart every unhealthy container; recovery behavior depends on the runtime and orchestration configuration.

17. Logging and Troubleshooting

Logs provide information about startup, request handling, configuration errors, dependency failures, and unexpected exceptions. A deployment process should include a clear method for viewing and retaining relevant logs.

17.1 Useful Diagnostic Commands

# Inspect running containers
docker ps

# View application output
docker logs myapp-container

# Follow logs in real time
docker logs -f myapp-container

# Inspect runtime configuration
docker inspect myapp-container

# Display the images available locally
docker image ls

17.2 Common Deployment Problems

Problem Possible Cause Recommended Action
HTTP 404 Incorrect context path or endpoint, or the application was not deployed. Check the WAR filename, URL, deployment status, and controller mappings.
HTTP 500 Unhandled application exception or failed dependency. Review application logs and exception stack traces.
Port already in use Another process is listening on the selected host port. Choose another host port or stop the conflicting process.
Container exits immediately Startup command failure, invalid configuration, or application crash. Inspect logs, exit status, and runtime configuration.
Database connection failure Incorrect credentials, hostname, port, firewall, or database availability. Verify connectivity and environment settings from the application environment.
Unsupported class version Application bytecode requires a newer Java runtime. Use a compatible runtime or rebuild for the required Java target.
WAR deployment fails Incompatible Tomcat version, missing dependencies, or invalid packaging. Check server logs, the WAR structure, and servlet API compatibility.
Application works locally but not in a container Missing configuration, filesystem assumptions, or network differences. Compare runtime settings, file paths, ports, and service names.

18. Production Deployment Best Practices

18.1 Security

  • Use supported Java and Tomcat versions with security updates.
  • Build images from trusted, maintained base images.
  • Run application processes as non-root users when possible.
  • Do not place secrets in Dockerfiles, source code, or image layers.
  • Restrict Tomcat Manager access and remove unnecessary administrative permissions.
  • Use HTTPS through a properly configured TLS endpoint or reverse proxy.
  • Scan application dependencies and container images for known vulnerabilities.
  • Apply least-privilege access to files, networks, and external services.

18.2 Reliability

  • Use health checks and meaningful application metrics.
  • Capture logs centrally where appropriate.
  • Set reasonable CPU, memory, and connection-pool limits.
  • Handle termination signals and shut down gracefully.
  • Keep persistent data outside disposable application containers.
  • Maintain tested backups and a documented recovery plan.
  • Use rolling deployment or other controlled release strategies where supported.

18.3 Image Management

  • Use meaningful version tags for release identification.
  • Track immutable image digests for production deployments.
  • Keep build steps repeatable and minimize unnecessary image contents.
  • Rebuild images when base images or security patches need updating.
  • Promote the same tested image through environments instead of rebuilding it differently for each stage.

19. CI/CD for Java Deployment

Continuous Integration and Continuous Delivery (CI/CD) automate the process of validating, packaging, and releasing applications. A pipeline reduces repetitive manual work and helps make releases traceable and repeatable.

19.1 Typical Pipeline Stages

  1. Checkout: Retrieve source code from version control.
  2. Build: Compile the Java application.
  3. Test: Run unit tests and integration tests.
  4. Package: Generate a JAR or WAR artifact.
  5. Scan: Check dependencies and artifacts for security issues.
  6. Build Image: Create a container image when container deployment is used.
  7. Publish: Upload the artifact or image to an approved repository.
  8. Deploy: Release the tested artifact to the target environment.
  9. Verify: Run smoke tests and health checks.
  10. Rollback: Restore the previous known-good release if verification fails.

19.2 Example Pipeline Logic

Checkout Source
      |
      v
Compile and Test
      |
      v
Package JAR or WAR
      |
      v
Security and Quality Checks
      |
      v
Build and Publish Image
      |
      v
Deploy to Staging
      |
      v
Smoke Tests and Health Checks
      |
      v
Production Release

The exact stages and tools depend on the team's source control, build system, artifact repository, deployment target, and release policy.

20. Practical Project: Deploy a Spring Boot REST API

In this project, you will build a small REST API, package it, and deploy it either to Tomcat as a WAR or to Docker as an executable JAR. Use one deployment approach first, then repeat the exercise with the alternative.

Step 1: Create a REST Controller

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class StatusController {

    @GetMapping("/api/status")
    public String status() {
        return "Application is running";
    }
}

Step 2: Build the Application

Run the Maven build and confirm that the expected artifact has been created.

mvn clean test package

Step 3A: Deploy as a WAR to Tomcat

  1. Configure the project for compatible WAR packaging.
  2. Build the WAR artifact.
  3. Copy it into the configured Tomcat application base directory.
  4. Check Tomcat logs for successful deployment.
  5. Test the endpoint at the deployed context path.

For a WAR named myapp.war, the endpoint might be:

http://localhost:8080/myapp/api/status

Step 3B: Deploy as a Dockerized JAR

Create a Dockerfile using the Java runtime version required by the application:

FROM eclipse-temurin:21-jre
WORKDIR /app
COPY target/myapp.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]

Build and start the image:

docker build -t myapp:1.0 .
docker run --name myapp-container -p 8080:8080 myapp:1.0

Test the endpoint:

http://localhost:8080/api/status

Step 4: Verify and Document

  • Record the Java and Tomcat versions used.
  • Confirm the application returns the expected response.
  • Check logs for warnings or exceptions.
  • Test what happens when the database or another required service is unavailable.
  • Document required environment variables and ports.
  • Write down the steps needed to roll back to a previous version.

21. Common Mistakes to Avoid

  • Deploying a WAR to a Tomcat version that does not support its Servlet or Jakarta API requirements.
  • Assuming every Spring Boot application must be packaged as a WAR.
  • Using localhost to reach a separate container without understanding container networking.
  • Hardcoding production credentials into source code or Dockerfiles.
  • Exposing the Tomcat Manager publicly without appropriate restrictions.
  • Publishing a container port without verifying which application port is listening inside the container.
  • Ignoring startup logs after deployment.
  • Using unversioned or unverified images for important production workloads.
  • Assuming a running container always means the application is healthy.
  • Updating production without a backup, verification plan, or rollback strategy.

22. Interview Questions and Answers

Q1. What is application deployment?

Answer: Application deployment is the process of packaging, configuring, releasing, and running software in a target environment so that users or other systems can access it.

Q2. What is Apache Tomcat?

Answer: Apache Tomcat is an open-source Java web server and servlet container used to run compatible Java web applications.

Q3. What is a WAR file?

Answer: A WAR file is a Web Application Archive that packages web application resources, compiled classes, and libraries in a standard format for deployment to a compatible servlet container.

Q4. How do you deploy a WAR file to Tomcat?

Answer: Build the WAR, copy it to the configured Tomcat application base directory or use an authorized Manager deployment method, inspect server logs, and test the resulting context path.

Q5. What is the purpose of the Tomcat Manager?

Answer: It provides administrative functions for deploying, starting, stopping, reloading, and undeploying web applications. It must be configured and protected appropriately.

Q6. What is Docker?

Answer: Docker is a platform used to build, distribute, and run container images. Containers provide isolated environments for application processes.

Q7. What is the difference between a Docker image and a container?

Answer: An image is a packaged, versioned template. A container is a running or stopped instance created from an image.

Q8. Can a Spring Boot application run without external Tomcat?

Answer: Yes. A Spring Boot executable JAR commonly includes an embedded server, allowing the application to run directly using the Java runtime.

Q9. Why might an application return HTTP 404 after deployment?

Answer: The context path may be incorrect, the endpoint mapping may not exist, or the application may not have deployed successfully. Verify the URL and server logs.

Q10. What is port mapping in Docker?

Answer: Port mapping forwards traffic from a host port to a port inside a container, such as -p 9090:8080.

Q11. Why should configuration be externalized?

Answer: External configuration allows the same artifact to run in different environments without rebuilding it for each environment. It also helps keep sensitive values out of source code.

Q12. What is a health check?

Answer: A health check evaluates whether an application or service is operating as expected. Liveness, readiness, and startup checks serve different purposes.

Q13. What is the role of CI/CD?

Answer: CI/CD automates build, test, packaging, security validation, release, deployment, and post-deployment verification tasks.

Q14. How do you troubleshoot a container that exits immediately?

Answer: Inspect its logs, exit status, startup command, runtime version, required configuration, and connectivity to dependent services.

Q15. Why is a rollback plan important?

Answer: A rollback plan helps restore a known-good release when a deployment introduces failures, reducing downtime and business impact.

23. Practice Exercises

  1. Install a compatible Tomcat version and verify that its home page is accessible.
  2. Build a simple Java web application and deploy it as a WAR.
  3. Change the WAR filename and observe how the default context path changes.
  4. Build a Spring Boot executable JAR and run it directly.
  5. Create a Docker image for the JAR and publish a host port.
  6. Deploy a WAR inside a Tomcat container.
  7. Configure an application profile through an environment variable.
  8. Intentionally use an incorrect endpoint and diagnose the resulting HTTP 404.
  9. Stop a dependent service and inspect the application's error handling.
  10. Write a short deployment guide that includes startup, verification, logs, and rollback steps.

24. Quick Revision Checklist

  • ☑ Understand Tomcat's role as a servlet container.
  • ☑ Know the differences between JAR, WAR, and container images.
  • ☑ Build and verify Java artifacts using Maven.
  • ☑ Deploy WAR files using Tomcat's application base directory or Manager.
  • ☑ Understand context paths and endpoint URLs.
  • ☑ Build and run Docker images for Java applications.
  • ☑ Configure ports, environment variables, and external services.
  • ☑ Read server and container logs to diagnose errors.
  • ☑ Configure appropriate health checks and monitoring.
  • ☑ Apply security, image management, and rollback best practices.

25. Conclusion

Deploying applications on Tomcat and container platforms is an essential skill for Java developers. Tomcat provides a runtime for compatible Java web applications, while containerization packages applications into portable runtime environments. A reliable deployment workflow combines correct packaging, compatible runtime versions, externalized configuration, secure credentials, health checks, log monitoring, automated testing, and a tested rollback strategy.

Practice both deployment approaches: deploying a WAR to a compatible Tomcat installation and running a Java application inside a Docker container. Understanding the strengths and limitations of each approach helps you choose an appropriate deployment model for different projects.

26. Additional Learning Resources

Previous Next
whatsapp