Multi-stage Dockerization of Spring Boot Application

Multi-stage Dockerization of Spring Boot Application

Multi-stage Docker builds help make your Docker image smaller by separating the build area from the runtime area. This is especially helpful for apps like Spring Boot, where you need build tools for compiling and packaging, but not in the final runtime image.

Here's an example of a multi-stage Dockerfile for a Spring Boot application:

# Stage 1: Build the application
FROM maven:3.8.4-openjdk-17-slim AS build
WORKDIR /app

# Copy only the necessary files for dependency resolution
COPY pom.xml .

# Download dependencies
RUN mvn dependency:go-offline

# Copy the rest of the application source code
COPY src/ /app/src/

# Build the application
RUN mvn package -DskipTests

# Stage 2: Create the runtime image
FROM openjdk:17-jdk-slim
WORKDIR /app

# Copy only the necessary artifacts from the build stage
COPY --from=build /app/target/my-spring-boot-app.jar my-spring-boot-app.jar

# Set the entry point for the application
CMD ["java", "-jar", "my-spring-boot-app.jar"]

Explanation of the Dockerfile:

  • Stage 1 (Build):

    • Use a Maven image as the build environment.

    • Copy only the pom.xml file first to leverage Docker cache for dependency resolution.

    • Download dependencies offline to cache them.

    • Copy the rest of the source code.

    • Build the application, skipping tests.

  • Stage 2 (Runtime):

    • Use a minimal OpenJDK image for the runtime environment.

    • Copy only the necessary artifacts (JAR file) from the build stage.

    • Set the entry point to run the Spring Boot application.

With multi-stage builds, the final image has only the compiled JAR file and the minimal runtime dependencies. This makes it smaller and safer. The build tools and intermediate artifacts from the compilation are removed after the first stage, creating a lighter runtime image.

Change the details of the Dockerfile to fit your project structure and needs. Also, remember to replace my-spring-boot-app.jar with the real name of your Spring Boot application JAR file.

Did you find this article valuable?

Support LingarajTechhub by becoming a sponsor. Any amount is appreciated!