Multi-stage builds with Maven
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A ShopLite image built from a jar on one laptop only works as well as that laptop: its Java version, its Maven settings, its files. Building inside Docker fixes that, and a second stage keeps the tools out of the final image.
The problem: building the jar on the host
A multi-stage build is a Dockerfile with more than one FROM. An early stage builds the jar with a JDK and Maven; the final stage copies only the finished jar into a small JRE image.
Example 1 runs Maven inside Docker, but in a single stage. The build becomes repeatable, and the image size shows what is still wrong.
Example 1 · Building inside Docker in one stage
Runs in: a Spring Boot project folder with Docker installed
# Dockerfile (single stage: builds and runs in one image)FROM eclipse-temurin:25-jdkWORKDIR /buildCOPY .mvn/ .mvn/COPY mvnw pom.xml ./COPY src ./srcRUN ./mvnw -B package -DskipTestsEXPOSE 8080ENTRYPOINT ["java", "-jar", "/build/target/shoplite-api-1.2.0.jar"]# Terminaldocker build -t shoplite-api:single .docker images shoplite-apiREPOSITORY TAG IMAGE ID CREATED SIZE shoplite-api single e2c97b10f4a6 20 seconds ago 697MB
What this code does
- Every computer now builds with the same JDK 25 image and the Maven version pinned by the wrapper, so the jar is the same everywhere.
- The price is size: the image keeps the JDK, the
/root/.m2folder with every downloaded library and plugin, the source code and the build output, about 697 MB. Your number will differ.
Building on the host means running ./mvnw package on your laptop and copying target/*.jar into the image. One teammate builds with Java 17, another with Java 25; one forgot to pull the latest code; the CI server has no target/ folder at all. The image is no longer reproducible: the "works on my machine" problem containers were meant to solve.
One stage fixes that, but the image then ships the JDK, the whole Maven download folder and the source code: about 700 MB. A second stage removes all of it.
Stage 1: FROM a JDK AS build
A stage starts at each FROM line and lasts until the next one. AS build gives a stage a name, so later stages can copy files out of it.
The build stage starts from a JDK, because Maven needs a compiler. It copies the project in and builds the jar.
FROM eclipse-temurin:25-jdk AS buildWORKDIR /buildCOPY .mvn/ .mvn/COPY mvnw pom.xml ./COPY src ./srcRUN ./mvnw -B package -DskipTestsExample 2 · Watching the Maven build inside the build stage
Runs in: a Spring Boot project folder with Docker installed
docker build --progress=plain -t shoplite-api:1.2.0 .#9 [build 6/6] RUN ./mvnw -B package -DskipTests #9 5.214 [INFO] Scanning for projects... #9 6.031 [INFO] Downloading from central: https://repo.maven.apache.org/maven2/org/springframework/boot/spring-boot-starter-parent/4.1.1/spring-boot-starter-parent-4.1.1.pom ... #9 41.87 [INFO] --- compiler:3.14.1:compile (default-compile) @ shoplite-api --- #9 44.02 [INFO] Compiling 63 source files with javac [debug parameters release 17] to target/classes #9 52.66 [INFO] Tests are skipped. #9 58.30 [INFO] --- spring-boot:4.1.1:repackage (repackage) @ shoplite-api --- #9 58.91 [INFO] Replacing main artifact /build/target/shoplite-api-1.2.0.jar with repackaged archive, adding nested dependencies in BOOT-INF/. #9 58.91 [INFO] The original artifact has been renamed to /build/target/shoplite-api-1.2.0.jar.original #9 58.93 [INFO] BUILD SUCCESS #9 DONE 59.6s
What this code does
--progress=plainprints every log line of every step;#9is the step number and5.214the seconds since that step started. The default view folds the log away once a step succeeds.- The first build downloads all dependencies from Maven Central, which is why this step takes about a minute. The Layer caching lesson makes later builds reuse them.
- The
repackagelines show Spring Boot turning the plain jar into the fat jar and keeping the plain one as.jar.original. Plugin versions and times depend on your project.
The Maven wrapper (mvnw plus the .mvn/ folder) is a small script that downloads the exact Maven version the project expects, so no Maven install is needed in the image. The Dockerfile copies it first, then pom.xml, then src.
-B is batch mode: no colours or progress bars, which keeps build logs readable. -DskipTests skips running tests here; the last section explains where they run instead. The finished jar ends up in /build/target/ inside this stage.
mvnw may have Windows (CRLF) line endings and the build fails with ./mvnw: not found or Permission denied. Add mvnw text eol=lf to .gitattributes, or run RUN chmod +x mvnw before using it.Stage 2: FROM a JRE, COPY --from=build
COPY --from=build copies files from the file system of the stage named build instead of from the build context. It is the only bridge between stages: nothing else crosses over.
The second FROM starts a fresh JRE image and takes just the jar from the build stage. This is the complete Dockerfile.
Example 3 · The complete multi-stage Dockerfile
Runs in: a Spring Boot project folder with Docker installed
# Stage 1: build the jar with a JDK and the Maven wrapperFROM eclipse-temurin:25-jdk AS buildWORKDIR /buildCOPY .mvn/ .mvn/COPY mvnw pom.xml ./COPY src ./srcRUN ./mvnw -B package -DskipTests# Stage 2: run the jar on a JREFROM eclipse-temurin:25-jreWORKDIR /appCOPY --from=build /build/target/*.jar app.jarEXPOSE 8080ENTRYPOINT ["java", "-jar", "/app/app.jar"][+] Building 71.4s (15/15) FINISHED docker:desktop-linux => [internal] load build definition from Dockerfile 0.0s => [internal] load metadata for docker.io/library/eclipse-temurin:25-jre 1.6s => [internal] load metadata for docker.io/library/eclipse-temurin:25-jdk 1.6s => [internal] load .dockerignore 0.0s => [build 1/6] FROM docker.io/library/eclipse-temurin:25-jdk@sha256:9b1e…c4d2 0.0s => [stage-1 1/3] FROM docker.io/library/eclipse-temurin:25-jre@sha256:4b6f…8abc 4.8s => [internal] load build context 0.1s => => transferring context: 214.6kB 0.1s => [build 2/6] WORKDIR /build 0.1s => [build 3/6] COPY .mvn/ .mvn/ 0.0s => [build 4/6] COPY mvnw pom.xml ./ 0.0s => [build 5/6] COPY src ./src 0.0s => [build 6/6] RUN ./mvnw -B package -DskipTests 59.6s => [stage-1 2/3] WORKDIR /app 0.1s => [stage-1 3/3] COPY --from=build /build/target/*.jar app.jar 0.3s => exporting to image 0.6s => => naming to docker.io/library/shoplite-api:1.2.0 0.0s
What this code does
- The build stage has six numbered steps,
[build 1/6]to[build 6/6]; the run stage has three, labelledstage-1because it has noASname. [stage-1 3/3] COPY --from=buildwaits for[build 6/6], because it needs the jar; the JRE download ran earlier, in parallel with the build.- Lines starting with
#in a Dockerfile are comments. Name every stage you copy from; numbers such as--from=0also work but break when someone adds a stage.
Only the last stage becomes the image that docker build -t names, so shoplite-api:1.2.0 contains the JRE, the folder /app and app.jar, and nothing from the build stage except that jar.
In the build output, stage steps are labelled with the stage name: [build 6/6], and [stage-1 3/3] for the unnamed second stage. BuildKit also starts both FROM downloads at the same time, so stages that do not depend on each other run in parallel.
Predict the output
What is in the final image?
Read the Dockerfile, then pick the answer.
Round 1 of 2
Is the folder /build/src present in the finished image?
WORKDIR, EXPOSE, exec-form ENTRYPOINT) are unchanged. Only the jar's source moved from your laptop to the build stage.What the final image leaves out, and the size before and after
The final stage is the last FROM in a multi-stage Dockerfile. Only it becomes the image you tag and push, so it holds just the JRE and the files copied in with COPY --from.
The final image has no Maven, no source and no JDK. Example 4 models what crosses over, and Example 5 checks the real image from the inside.
Example 4 · A model of what crosses from build to final
import java.util.LinkedHashMap;import java.util.Map;
class Stage { final String name; final String baseImage; final int baseMb; final Map<String, Integer> files = new LinkedHashMap<>();
Stage(String name, String baseImage, int baseMb) { this.name = name; this.baseImage = baseImage; this.baseMb = baseMb; }
int totalMb() { int total = baseMb; for (int size : files.values()) { total += size; } return total; }}
public class StageCopyDemo { // Matches the glob <dir>/*.jar: a file directly inside dir whose name ends in .jar static boolean matchesJarGlob(String path, String dir) { if (!path.startsWith(dir + "/")) { return false; } String rest = path.substring(dir.length() + 1); return !rest.contains("/") && rest.endsWith(".jar"); }
public static void main(String[] args) { Stage build = new Stage("build", "eclipse-temurin:25-jdk", 452); build.files.put("/root/.m2/repository", 180); build.files.put("/build/src", 1); build.files.put("/build/target/classes", 1); build.files.put("/build/target/shoplite-api-1.2.0.jar", 62); build.files.put("/build/target/shoplite-api-1.2.0.jar.original", 1);
Stage run = new Stage("final", "eclipse-temurin:25-jre", 268);
System.out.println("COPY --from=build /build/target/*.jar /app/app.jar"); for (Map.Entry<String, Integer> file : build.files.entrySet()) { if (matchesJarGlob(file.getKey(), "/build/target")) { run.files.put("/app/app.jar", file.getValue()); System.out.println(" copied " + file.getKey()); } else { System.out.println(" left " + file.getKey()); } }
System.out.println(); System.out.println(build.name + " stage (" + build.baseImage + "): " + build.totalMb() + " MB"); System.out.println(run.name + " image (" + run.baseImage + "): " + run.totalMb() + " MB"); System.out.println("Shipped to the server: only the " + run.name + " image"); }}COPY --from=build /build/target/*.jar /app/app.jar left /root/.m2/repository left /build/src left /build/target/classes copied /build/target/shoplite-api-1.2.0.jar left /build/target/shoplite-api-1.2.0.jar.original build stage (eclipse-temurin:25-jdk): 697 MB final image (eclipse-temurin:25-jre): 330 MB Shipped to the server: only the final image
What this code does
- Each
Stageis a base image plus files with sizes in MB (rough numbers for ShopLite).matchesJarGlobfollows the glob rule:*matches any name inside one folder, so.jar.originaland anything in subfolders do not match. - Only one file crosses over; the 180 MB Maven folder, the source and the classes stay in the build stage, which is not part of the final image.
- This is a simplified model for learning, not how Docker stores layers, but the sizes it prints match the real images in Example 5 closely.
Example 5 · Checking the final image from the inside
Runs in: a Spring Boot project folder with Docker installed
docker images shoplite-api# Look inside the final image with a throwaway shelldocker run --rm --entrypoint sh shoplite-api:1.2.0 -c \ "ls /app; command -v javac || echo 'no javac'; command -v mvn || echo 'no mvn'; ls /build || echo 'no /build'"REPOSITORY TAG IMAGE ID CREATED SIZE shoplite-api 1.2.0 9a3f5e27c1d0 2 minutes ago 330MB shoplite-api single e2c97b10f4a6 30 minutes ago 697MB app.jar no javac no mvn ls: cannot access '/build': No such file or directory no /build
What this code does
- The multi-stage image is less than half the size of the single-stage one. Sizes differ by Docker version and platform; compare your own with
docker images. --entrypoint shreplacesjava -jarfor this one throwaway container, so you can run shell commands inside the image.command -vprints a program's path, or fails when the program is missing.- Only
app.jaris in/app; there is nojavac, nomvnand no/buildfolder with source code.
The Maven download folder (/root/.m2, often 150 to 250 MB), the compiled classes, the .jar.original file and the JDK tools all stay behind in the build stage.
That makes the image smaller (about 330 MB instead of about 700 MB for ShopLite) and safer: no source code to leak, and no compiler or build tool for an attacker. It is also faster to push to a registry and to pull on every server.
Find the bug
Why is this image still big?
Tap the line that keeps the build tools in the final image.
The image works but is about 700 MB. Which line is the problem?
Round 1 of 2Where tests run: in CI, not in the image build
CI (continuous integration) is a server that builds and tests every push automatically. ShopLite's tests run there with ./mvnw verify; the image build only packages code that has already passed.
The pipeline below runs the tests first and builds the image only if they pass.
# What a CI pipeline runs for every push (the CI/CD module builds this)./mvnw -B verify # all tests, test reportsdocker build -t shoplite-api:1.2.0 . # package the tested code (-DskipTests inside)Running tests inside docker build has real costs. Every image build becomes minutes slower, the test reports are trapped inside a throwaway stage, and Testcontainers tests need a running Docker, which a build step does not have.
The CI/CD with GitHub Actions module sets this pipeline up.
Order of execution
A safe pipeline for ShopLite
Tap the steps in the order the pipeline runs them.
FROM build AS test with RUN ./mvnw -B verify) and run it with docker build --target test .. BuildKit skips stages the final image does not need, so normal builds stay fast.Next step
Check your understanding
11 quick questions