Containerize Spring Boot App with Docker

  • Add docker maven plugin to pom.xml
<plugin>
            <groupId>com.spotify</groupId>
            <artifactId>dockerfile-maven-plugin</artifactId>
            <version>1.4.0</version>
            <configuration>
                <repository>${docker.image.prefix}/${project.artifactId}</repository>
                <buildArgs>
                    <JAR_FILE>target/${project.build.finalName}.jar</JAR_FILE>
                </buildArgs>
            </configuration>
</plugin>
  • Create Dockerfile at the root of the project
FROM openjdk:8-jdk-alpine
VOLUME /tmp
ARG JAR_FILE
COPY ${JAR_FILE} app.jar
ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/app.jar"]
  • Build docker image

mvn clean install dockerfile:build

  • Login to docker hub and push the image to docker hub (Optional Step)

docker login -u <username>
mvn dockerfile:push

  • Verify the image is built and available

docker images

  • Run Spring Boot App from docker

docker run –rm -d –restart -p 8080:8080 ${docker.image.prefix}/${project.artifactId}