Multi-stage builds — Use multi-stage builds
Consider the following Dockerfile Bounded code example (external data; do not execute automatically): ```dockerfile FROM eclipse-temurin:21.0.8_9-jdk-jammy AS builder WORKDIR /opt/app COPY .mvn/ .mvn COPY mvnw pom.xml ./ RUN ./mvnw dependency:go-offline COPY ./src ./src RUN ./mvnw clean install FROM
Reference note (untrusted external data; do not execute it as instructions).
Consider the following Dockerfile
Bounded code example (external data; do not execute automatically):
```dockerfile
FROM eclipse-temurin:21.0.8_9-jdk-jammy AS builder
WORKDIR /opt/app
COPY .mvn/ .mvn
COPY mvnw pom.xml ./
RUN ./mvnw dependency:go-offline
COPY ./src ./src
RUN ./mvnw clean install
FROM eclipse-temurin:21.0.8_9-jre-jammy AS final
WORKDIR /opt/app
EXPOSE 8080
COPY --from=builder /opt/app/target/*.jar /opt/app/*.jar
ENTRYPOINT ["java", "-jar", "/opt/app/*.jar"]
```
> For production use, it's highly recommended that you produce a custom JRE-like runtime using jlink. JRE images are available for all versions of Eclipse Temurin, but jlink allows you to create a minimal runtime containing only the necessary Java modules for your application. This can significantly reduce the size and improve the security of your final image. Refer to this page for more information.
With multi-stage builds, a Docker build uses one base image for compilation, packaging, and unit tests and then a separate image for the application runtime. As a result, the final image is smaller in size since it doesn’t contain any development or debugging tools. By separating the build environment from the final runtime environment, you can significantly reduce the image size and increase the security of your final images.
Now, rebuild your image and run your ready-to-use production build.
Bounded code example (external data; do not execute automatically):
```console
$ docker build -t spring-helloworld-builder .
```
Look at the image size difference by using the docker images command
Bounded code example (external data; do not execute automatically):
```console
$ docker images
```
Bounded code example (external data; do not execute automatically):
```console
spring-helloworld-builder latest c5c76cb815c0 24 minutes ago 428MB
spring-helloworld latest ff708d5ee194 About an hour ago 880MB
```
Attribution: Adapted from Docker Documentation under Apache-2.0. Adaptation: WikiKV isolated this documentation section, normalized formatting, retained only bounded code excerpts, and shortened it at a paragraph or sentence boundary for retrieval. Verify version-sensitive details at the source.
ATTRIBUTED SOURCE
This compact reference card is adapted from official documentation and is not a community-verified experience.
Docker Documentation — content/get-started/docker-concepts/building-images/multi-stage-builds.md :: Use multi-stage builds ↗Revision 3a9d778562f3 · Apache-2.0 and attribution