What are multi-stage builds and why do they shrink and secure images?
Take a moment.
Say your answer out loud or write it down first — retrieval is what makes it stick. Reveal when you're ready.
Short answer
One Dockerfile, multiple FROM stages: a builder stage with compilers/toolchains produces artifacts, and a slim runtime stage COPY --from=builder only the artifacts. Final images drop build tools — the docs' Spring app halves from 880 MB (JDK+Maven) to 428 MB (JRE-only) with a smaller attack surface.
Detailed explanation
Single-stage builds ship everything used to build: JDK, Maven, caches, source. Multi-stage splits concerns with FROM … AS <name> per stage and COPY --from=<stage> to ferry results forward; the default build target is the last stage (--target builder builds an earlier one for debugging). Pattern: FROM eclipse-temurin:21-jdk AS builder → COPY mvnw/pom → RUN ./mvnw dependency:go-offline (cached deps) → COPY src → RUN ./mvnw clean install; then FROM eclipse-temurin:21-jre AS final → COPY --from=builder /opt/app/target/*.jar /opt/app/ → ENTRYPOINT java -jar. Interpreted stacks benefit too: build/minify JS in a Node stage, ship static files on nginx. Security follows size — no compiler, package manager, or source in production means fewer CVEs to exploit. For best results generate a minimal JRE with jlink rather than shipping a full JRE.
Official docs:Docker docs: Multi-stage builds
Example
# Stage 1: build with full toolchain
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
# Stage 2: slim runtime, artifacts only
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/app.jar
ENTRYPOINT ["java", "-jar", "/opt/app/app.jar"]Interview tip
Contrast the two FROMs by job — 'build needs a toolchain, runtime needs a binary' — and cite the 880→428 MB halving as proof. Mention --target for debugging cred.
Common mistakes
- Shipping the SDK/toolchain in the final image.
- Not naming stages and COPYing whole directories instead of just artifacts.