0
0
Spring Bootframework~5 mins

Multi-stage Docker builds in Spring Boot

Choose your learning style9 modes available
Introduction

Multi-stage Docker builds help you create smaller and faster Docker images by separating the build and runtime steps.

When you want to build a Spring Boot app and keep the final image small.
When you want to avoid including build tools like Maven or Gradle in the final image.
When you want faster deployment by reducing image size.
When you want to keep your Dockerfile clean and organized.
When you want to improve security by excluding unnecessary files from the final image.
Syntax
Spring Boot
FROM <build-image> AS build
# build steps here

FROM <runtime-image>
COPY --from=build <source> <destination>
CMD ["java", "-jar", "app.jar"]

The AS build names the first stage so you can copy files from it later.

The final stage uses a smaller image to run the app, copying only needed files.

Examples
This example builds a Spring Boot app using Maven, then copies the jar to a smaller OpenJDK image.
Spring Boot
FROM maven:3.8.6-openjdk-17 AS build
WORKDIR /app
COPY pom.xml .
COPY src ./src
RUN mvn clean package -DskipTests

FROM openjdk:17-jdk-slim
WORKDIR /app
COPY --from=build /app/target/myapp.jar ./app.jar
CMD ["java", "-jar", "app.jar"]
This example uses Gradle to build the app, then copies the jar to a lightweight runtime image.
Spring Boot
FROM gradle:7.5-jdk17 AS build
WORKDIR /app
COPY build.gradle settings.gradle ./
COPY src ./src
RUN gradle build --no-daemon

FROM openjdk:17-jdk-slim
WORKDIR /app
COPY --from=build /app/build/libs/*.jar ./app.jar
CMD ["java", "-jar", "app.jar"]
Sample Program

This Dockerfile first builds the Spring Boot app using Maven in the build stage. Then it copies the built jar file into a smaller OpenJDK image to run the app. This keeps the final image small and clean.

Spring Boot
FROM maven:3.8.6-openjdk-17 AS build
WORKDIR /app
COPY pom.xml .
COPY src ./src
RUN mvn clean package -DskipTests

FROM openjdk:17-jdk-slim
WORKDIR /app
COPY --from=build /app/target/demo-0.0.1-SNAPSHOT.jar ./app.jar
CMD ["java", "-jar", "app.jar"]
OutputSuccess
Important Notes

Always use a smaller runtime image like openjdk:17-jdk-slim for the final stage to reduce image size.

Use --from=build to copy files from the build stage by its name.

Skipping tests during build can speed up image creation but only do this if tests are run elsewhere.

Summary

Multi-stage builds separate building and running your app to keep images small.

Use a full image with build tools first, then copy only needed files to a smaller runtime image.

This method improves deployment speed, security, and image cleanliness.