Spring Boot Docker

So I am learning docker and I gotta say, it's awesome. Spinning up the application you want with a single command is so convenient. This blog is for me to reference but I hope it helps you too.

Image that runs in a container - that's what docker is.

Now for creating the docker image of Spring Boot Gradle Application

  1. Create a file named Dockerfile in the source directory which is used to build the docker image.

  2. Add the following code

# Stage 1: Build Stage
FROM bellsoft/liberica-openjdk-alpine:17.0.7-7 as builder
WORKDIR /app

COPY build.gradle .
COPY settings.gradle .
COPY gradlew .
COPY gradle ./gradle
COPY src ./src

RUN ./gradlew --no-daemon clean build

# Stage 2: Run the application
FROM bellsoft/liberica-runtime-container:jre-17-slim-musl
WORKDIR /app
COPY --from=builder /app/build/libs/application.jar /app/application.jar
EXPOSE 8080

ENTRYPOINT ["java", "-jar", "/app/application.jar"]

This is a multi-stage build docker file for spring boot application. In the first stage, we copy the necessary files into the image and build the application, and in the second stage, we copy the jar file from first stage and create the entry point.

By default, only the last stage files are saved in the image. So the source and all other files are not part of the final image. and the image contains only jar file. This drastically reduces the image size and improves security as there are only necessary files.

Always use mutli-stage builds in Dockerfile, If possible

  1. Now finally the building the image

     docker build -t my-app-image .
    
  2. The above command builds the image, and to run the the image

     docker run --name my-app -p 8080:8080 my-app-image:latest
    

And That's it, your application should be up and running.

Note that if you make any changes in the code, rebuild the image and run it to see the changes.