Building Tomcat Docker image for your side project

I assume you know what Tomcat and Docker are. Tomcat image by default has no user and no application deployed. It was designed to fork the image and use it with your own configuration. I couldn’t find any introduction which shows how to deploy your own Tomcat with user management enabled for your side projects. Everything was either too complex for my needs or did not answer the question “how to deploy Tomcat to play with it, deploy in it, destroy it”.

So, here I wrote a simple snippet that builds a local Tomcat docker image with your username and password and enables you to run Spring-Boot project, login from remote IP address (by default you can login only from IP Tomcat is running on).

  1. You need your own Dockerfile which forks Tomcat
  2. tomcat-users.xml file which contains roles, username and password
  3. context.xml file which enables you to login to Tomcat instance from remote IP

You can clone my Tomcat repository from GitLab, modify tomcat-users.xml with your own username and password and built it locally, but here you can see all the source code I used in the repository.

Source for the Dockerfile the image forks tomcat:8.0-jre8, copies local user management file and context to the image. Of course it has to expose port 8080 where Tomcat will be listening for connections:

FROM tomcat:8.0-jre8
MAINTAINER info@agilob.net
COPY tomcat-users.xml /usr/local/tomcat/conf/tomcat-users.xml
COPY context.xml /usr/local/tomcat/webapps/manager/META-INF/context.xml
EXPOSE 8080/tcp

tomcat-users.xml contains list of users, their roles and passwords, it’s simple as that:

<!--?xml version="1.0" encoding="UTF-8"?-->
<tomcat-users xmlns="http://tomcat.apache.org/xml"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://tomcat.apache.org/xml tomcat-users.xsd"
              version="1.0">
  <user username="user" password="password" roles="admin-gui,admin-script,manager-gui,manager-script,manager-status,manager-jmx"/>
</tomcat-users>

The next one is context.xml which allows you to login to a remote server using your home IP (I deploy Tomcat on my dedicated server and connect to it from home):

<?xml version="1.0" encoding="UTF-8"?>
<Context antiResourceLocking="false" privileged="true" >
    <!--
    <Valve className="org.apache.catalina.valves.RemoteAddrValve"
         allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1" />
    -->
</Context>

The last part of my setup is to automate the build process. I want to build the image and automatically deploy it in local Docker:

#!/bin/bash -e
docker build . | tee .log.txt
TAG=`cat .log.txt | tail -n1 | awk 'NF>1{printf $NF}'`
docker run --restart=always -it -p 8080:8080 $TAG

Now, when you run bash ./build.sh as root, it will automatically build the image for you and start it.