In my previous post, we discussed how to deploy a SpringBoot WAR file into Tomcat running in Docker
Deploying Spring Boot War in Tomcat based Docker
Steps to Dockerize Spring Boot Application
medium.com
Here in this post, we are going to see how to run SpringBoot Web application JAR file directly in Docker
Wait ! How come a Java Web Application can run without deploying in an Application Server like Tomcat/Jetty ?
SpringBoot came up with a clever idea to achieve it. When you add Spring-Boot-Starter-Web dependency, it adds Embedded Tomcat JAR file to our class path
Embedded Tomcat Jar (Embedded Jetty/UnderTow also available) can do all things standalone Tomcat can do expect that Embedded Tomcat Jar is packed along with our application JAR file
Lets take my sample Spring Boot Application (Refer here : https://github.com/iamvickyav/spring-boot-data-H2-embedded)
My application uses maven, so here is the commands to run the application
> mvn clean package
> java -jar target/spring-h2-demo.jar
Once we verify the application running successfully in local, we can containerize the application.
Lets start with creating a Dockerfile in root directory of the project
FROM openjdk:8-jre-slim
WORKDIR /home
COPY /target/spring-h2-demo.jar spring-h2-demo.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "spring-h2-demo.jar"]
DockerFile demystified
FROM — Base image on top of which our custom image is to be build
WORKDIR — To define the working directory. CMD, ENTRYPOINT commands will run from this directory only
COPY — Copy JAR file into WORKDIR
EXPOSE — Expose port 8080 outside Docker container
ENTRYPOINT — The command to be executed when the docker run command executed
To build & run the docker image
> mvn clean package
> docker build -t my-image .
> docker run -p 8080:8080 my-image
Note: There is a . (dot) at the end of the docker build command to specify current directory
Thats all folks !!!