Multi-stage Docker builds help you create smaller and faster Docker images by separating the build and runtime steps.
Multi-stage Docker builds in 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.
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"]
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"]
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.
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"]
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.
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.