Table of Contents
How to create docker image of spring MVC project
Well, when it comes to running an existing spring MVC project say which was done a couple of years ago when spring boot was a novice or not as popular and now you want to port out the spring MVC application without making it a Spring boot app due to any issue.
The good news is it is very simple to create a docker image of Spring MVC project and run as a docker container
In this tutorial, I will be using Tomcat but you can choose other applications servers too.
How to do it?
Well, get your thinking hat on. In spring boot we embed Tomcat application server and run our app on top of it, now what about running our application in a Tomcat standalone server?
Yes, that’s all we will do. We will get a Tomcat Image and deploy our WAR on top of it.
In the project root folder, you need to create a docker file which should be named as Dockerfile without any extension. In this file, we will add couple of steps
COPY /target/myApplication.war /usr/local/tomcat/webapps/
The first line suggests that get the tomcat Image from Docker hub
The second line is suggesting that copy your war file to tomcat’s web apps directory where it will be installed.
If you are familiar with Tomcat you would know that any WAR file in the webapps folder will be installed on server start up.
You can use docker file commands like RUN, COPY, itsADD etc to update config folder, for eg RUN rm -rf /usr/local/tomcat/webapps/ROOT will remove/uninstall the existing ROOT application.
Create Docker Image
Once you have the docker file ready in your project, we need to create a Docker image.
To create a Docker Image open Terminal/command Prompt and then navigate to the project root directory and build the docker image ( You need to have docker installed on your system)
docker build -t myapp .
(don’t miss “.�? , as it tells docker file is in current directory)
If the above command is successful then use docker images see if the image has been created.There should be a docker image called myapp
REPOSITORY TAG IMAGE ID CREATED SIZE
myapp latest 36ada7cb0f68 6 seconds ago 539 MB
Run Docker Image
docker run -d -p 8080:8080 --name mydockerapp myapp
We are asking docker here to run our application on localhost port 8080, and since we know that our Tomcat started on port 8080 by default so we are pointing to that port within docker. The docker assigns some random name each time docker is restarted it’s good practice to name the docker image and we have done that using –name tag so our docker container will be called as mydockerapp.
If above command was successful use, docker ps -a it should show the running images under names columns you should see the mydockerapp
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
45046a198154 myapp "catalina.sh run" 9 seconds ago Up 8 seconds 0.0.0.0:8080->8080/tcp mydockerapp
The docker container is running on 8080 port, so your application should be available on localhost:8080/mydockerapp/