Dockerise a Tomcat application

Create a Dockerfile.

This file describes how to build an image for your application. Here is an example of a basic Dockerfile that can be used for a Tomcat application:

FROM tomcat:9.0
COPY [path-to-war-file] /usr/local/tomcat/webapps/[application-name].war

This Dockerfile uses the official Tomcat 9.0 image as the base image and copies the WAR file for your application to the webapps directory in the Tomcat container.

Building the image

Run the following command in the same directory as the Dockerfile:

docker build -t [image-name] .

Starting the container

Run the following command: docker run -p 8080:8080 [image-name]

This command maps port 8080 on the host to port 8080 in the container and starts the [image-name] container.

Your application is now accessible here: http://localhost:8080/[application-name]

Docker compose

An example docker-compose.yml file that includes the above Tomcat application as well as a MySQL database and RabbitMQ:

version: '3'
services:
  db:
    image: mysql:8.0
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: [root-password]
      MYSQL_DATABASE: [database-name]
      MYSQL_USER: [username]
      MYSQL_PASSWORD: [password]

  rabbitmq:
    image: rabbitmq:3-management
    restart: always
    ports:
      - "15672:15672"
      - "5672:5672"
    environment:
      RABBITMQ_DEFAULT_USER: [username]
      RABBITMQ_DEFAULT_PASS: [password]

  yourtomcat:
    build: .
    ports:
      - "8080:8080"
    environment:
      - CATALINA_OPTS=-Xms512m -Xmx1024m
      - SPRING_RABBITMQ_HOST=rabbitmq
      - SPRING_DATASOURCE_URL=jdbc:mysql://db:3306/[database-name]
      - SPRING_DATASOURCE_USERNAME=[username]
      - SPRING_DATASOURCE_PASSWORD=[password]
    volumes:
      - [path-to-war-file]:/usr/local/tomcat/webapps/[application-name].war

    depends_on:
      - db
      - rabbitmq

This docker-compose.yml file includes three services:

Building the services

Run the following command from the directory containing the docker-compose.yml file: docker-compose --build

Starting the services

To start the containers run docker-compose up. Optionally, you can pass -d to run the services detached.

You can now access your application by navigating to http://localhost:8080/[application-name] in a web browser.