Adding user to Tomcat in Docker

When using official Tomcat server from Docker Hub you will face a problem with opening management UI, because there is no default login or password in that docker image, so the only app management site you can visit is this one:

And because Tomcat doesn’t have user management built-in like other container managers – it loads users and passwords from conf/tomcat-users.xml file, it makes it more complicated to start with Tomcat than with other container managers like Wildfly.

The Tomcat Docker image comes without nano, vi or vim… so you can’t easily edit that file, but hopefully it comes with.. sed. And that’s good enough to add new users and roles to the file! Remember the times when you didn’t see the file you were editing when you when typing, until vi came out of course?

On my setup, the Tomcat image has name “tomcat”. To connect to the image with interactive shell use the command below:

docker exec -i -t CONTAINER_NAME /bin/bash

Which for me is:

docker exec -i -t tomcat /bin/bash

Now, you should be in shell that does NOT store history, so once you turn it off, you lose history, that’s good, it’s for your security.
To edit the config file and add your user do:

cd conf/
sed -i '$ d' tomcat-users.xml # removes last line
echo '<user username="YOUR_USERNAME" password="YOUR_PASSWORD" roles="admin-gui,admin-script,manager-gui,manager-script,manager-status,manager-jmx"/>' >> tomcat-users.xml
echo '</tomcat-users>' >> tomcat-users.xml # add removed last line back

Obviously, change username and password tag to whatever you want. Now, just restart the docker container:

docker restart tomcat

This is a silly solution, but it works.