In the previous section Spring Boot With Executable Jar, we learnt how to build an executable jar file from Spring Boot project. Now we will continue to build a docker image with an executable jar file and then we can use this image to deploy our spring boot application on any server which support container technology.
So firstly, we need to write a Dockerfile. A Dockerfile is a text file that contains the instructions for building a Docker image. A Docker image is a lightweight, standalone, executable package of software that includes everything needed to run an application: code, runtime, system tools, system libraries and settings.
So after building the Spring Boot application and got the executable jar file. We will create a Dockerfile as below.
Dockerfile
1 2 3 4 5 6 7 8 91011121314
# Use the base image with Java 8 and Alpine LinuxFROMopenjdk:8# Set the working directory in the containerWORKDIR/app# Copy the compiled Spring Boot application JAR file into the containerCOPYtarget/json-schema-validator-0.0.1-SNAPSHOT.jar/app/json-schema-validator-0.0.1-SNAPSHOT.jar
# Expose the port that the Spring Boot application listens onEXPOSE8080# Set the command to run the Spring Boot application when the container startsCMD["java","-jar","-Dspring.profiles.active=dev","json-schema-validator-0.0.1-SNAPSHOT.jar"]
Commands
Description
FROM openjdk:8
This specifies the base image to use for the Docker image. In this case, it is using the official OpenJDK 8 image with Alpine Linux as the base operating system. This image provides Java 8 runtime environment.
WORKDIR /app
This sets the working directory inside the container to /app. It's a good practice to use a specific directory for your application.
This copies the compiled Spring Boot application JAR file from the target directory of the host machine into the /app directory of the container. The source file is json-schema-validator-0.0.1-SNAPSHOT.jar in the target directory, and the destination is /app/json-schema-validator-0.0.1-SNAPSHOT.jar in the container.
EXPOSE 8080
This declares that the Spring Boot application listens on port 8080 inside the container. It does not actually publish the port to the host machine, but it provides a hint to users of the image about the exposed port.
This is the command that will be executed when the container starts. It runs the Spring Boot application using the java -jar command. The -Dspring.profiles.active=dev part sets the active Spring profile to dev. The json-schema-validator-0.0.1-SNAPSHOT.jar is the JAR file that will be executed.