Layer caching for faster builds
45 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Every small change to ShopLite takes a full minute to rebuild, because Docker downloads all the dependencies again. Ordering the Dockerfile so that slow steps rarely change turns that minute into about twenty seconds.
How the build cache works
The build cache is Docker's memory of every step it has built. A step is reused, and printed as CACHED, when its cache key is unchanged: the layer above it, the instruction text and, for COPY, a checksum of the copied files.
Example 1 is a small model of Docker's cache in plain Java. It builds the same six-step Dockerfile several times and prints which steps run.
Example 1 · A tiny model of the layer cache
import java.util.HashMap;import java.util.HashSet;import java.util.List;import java.util.Map;import java.util.Set;
class Step { final String instruction; final int seconds; final List<String> inputs;
Step(String instruction, int seconds, String... inputs) { this.instruction = instruction; this.seconds = seconds; this.inputs = List.of(inputs); }}
class BuildCache { private final Set<String> known = new HashSet<>();
void build(String title, List<Step> steps, Map<String, String> files) { System.out.println(title); String parentKey = ""; int total = 0; for (int i = 0; i < steps.size(); i++) { Step step = steps.get(i); // Key = the step above + this instruction + the content of the files it copies StringBuilder key = new StringBuilder(parentKey).append(" > ").append(step.instruction); for (String input : step.inputs) { key.append(" ").append(input).append("@").append(files.get(input)); } String label = "[" + (i + 1) + "/" + steps.size() + "] " + step.instruction; if (known.contains(key.toString())) { System.out.println(" CACHED " + label); } else { System.out.println(" RUN " + label + " (" + step.seconds + "s)"); known.add(key.toString()); total += step.seconds; } parentKey = key.toString(); } System.out.println(" Build time: " + total + "s"); System.out.println(); }}
public class LayerCacheDemo { public static void main(String[] args) { List<Step> steps = List.of( new Step("FROM eclipse-temurin:25-jdk", 9), new Step("WORKDIR /build", 0), new Step("COPY mvnw pom.xml ./", 1, "mvnw", "pom.xml"), new Step("RUN ./mvnw -B dependency:go-offline", 45), new Step("COPY src ./src", 1, "src"), new Step("RUN ./mvnw -B package -DskipTests", 20));
Map<String, String> files = new HashMap<>(); files.put("mvnw", "v1"); files.put("pom.xml", "v1"); files.put("src", "v1");
BuildCache cache = new BuildCache(); cache.build("Build 1: empty cache", steps, files);
files.put("src", "v2"); cache.build("Build 2: edited ProductController.java", steps, files);
files.put("pom.xml", "v2"); cache.build("Build 3: added a dependency to pom.xml", steps, files); }}Build 1: empty cache RUN [1/6] FROM eclipse-temurin:25-jdk (9s) RUN [2/6] WORKDIR /build (0s) RUN [3/6] COPY mvnw pom.xml ./ (1s) RUN [4/6] RUN ./mvnw -B dependency:go-offline (45s) RUN [5/6] COPY src ./src (1s) RUN [6/6] RUN ./mvnw -B package -DskipTests (20s) Build time: 76s Build 2: edited ProductController.java CACHED [1/6] FROM eclipse-temurin:25-jdk CACHED [2/6] WORKDIR /build CACHED [3/6] COPY mvnw pom.xml ./ CACHED [4/6] RUN ./mvnw -B dependency:go-offline RUN [5/6] COPY src ./src (1s) RUN [6/6] RUN ./mvnw -B package -DskipTests (20s) Build time: 21s Build 3: added a dependency to pom.xml CACHED [1/6] FROM eclipse-temurin:25-jdk CACHED [2/6] WORKDIR /build RUN [3/6] COPY mvnw pom.xml ./ (1s) RUN [4/6] RUN ./mvnw -B dependency:go-offline (45s) RUN [5/6] COPY src ./src (1s) RUN [6/6] RUN ./mvnw -B package -DskipTests (20s) Build time: 67s
What this code does
- Each step's key is the previous key plus its instruction plus the version of each file it copies. A step is
CACHEDwhen its key was seen before; the timings are made-up round numbers. - Build 2 changed only
src, so steps 1 to 4 keep their keys and the 45-second download is skipped: 21 seconds instead of 76. - Build 3 changed
pom.xml: step 3 gets a new key, which changes the parent key of every step below, so steps 3 to 6 all run.
When the key matches, the step is CACHED. When it does not, the step runs and every step below it runs too, because its "layer above" is now new. So a change near the top of a Dockerfile is expensive and a change near the bottom is cheap: editing one Java file invalidates COPY src ./src and everything after it, but not the steps before it.
For RUN, only the command text counts. Docker does not know whether RUN ./mvnw dependency:go-offline would download something new today; it reuses the old layer until a step above changes. docker build --no-cache forces every step to run.
Predict the output
Which steps run again?
Read the Dockerfile, then pick the steps Docker has to run.
Round 1 of 3
You edit one Java file and rebuild.
Order matters: pom.xml and go-offline before src
./mvnw -B dependency:go-offline is a Maven command that downloads the project's dependencies and plugins into /root/.m2 without building anything, so Docker can save the download in a layer of its own.
Put what changes least at the top. The Dockerfile below copies pom.xml, downloads the dependencies, and only then copies src and builds.
FROM eclipse-temurin:25-jdk AS buildWORKDIR /buildCOPY .mvn/ .mvn/COPY mvnw pom.xml ./RUN ./mvnw -B dependency:go-offlineCOPY src ./srcRUN ./mvnw -B package -DskipTestsExample 2 · Rebuilding after a code change
Runs in: a Spring Boot project folder with Docker installed
# DockerfileFROM eclipse-temurin:25-jdk AS buildWORKDIR /buildCOPY .mvn/ .mvn/COPY mvnw pom.xml ./RUN ./mvnw -B dependency:go-offlineCOPY src ./srcRUN ./mvnw -B package -DskipTestsFROM eclipse-temurin:25-jreWORKDIR /appCOPY --from=build /build/target/*.jar app.jarEXPOSE 8080ENTRYPOINT ["java", "-jar", "/app/app.jar"]# Terminal: build once, edit ProductController.java, build againdocker build -t shoplite-api:1.2.0 .docker build -t shoplite-api:1.2.0 .[+] Building 22.6s (16/16) FINISHED docker:desktop-linux => [internal] load build context 0.1s => => transferring context: 3.41kB 0.0s => [build 1/7] 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 0.0s => CACHED [build 2/7] WORKDIR /build 0.0s => CACHED [build 3/7] COPY .mvn/ .mvn/ 0.0s => CACHED [build 4/7] COPY mvnw pom.xml ./ 0.0s => CACHED [build 5/7] RUN ./mvnw -B dependency:go-offline 0.0s => [build 6/7] COPY src ./src 0.1s => [build 7/7] RUN ./mvnw -B package -DskipTests 19.8s => CACHED [stage-1 2/3] WORKDIR /app 0.0s => [stage-1 3/3] COPY --from=build /build/target/*.jar app.jar 0.3s => exporting to image 0.5s
What this code does
- The output is from the second build. Steps 2 to 5 of the build stage are
CACHED, including the dependency download; the first step that ran is[build 6/7] COPY src ./src, where the change entered. transferring context: 3.41kBshows BuildKit sends only changed files after the first build. Times depend on your machine and project.- In the final stage only the
COPY --fromre-ran, because the jar is new. The whole jar, all 60 MB, becomes a new layer: the layered jar section fixes that.
You edit Java files many times a day but change pom.xml maybe once a week. With this order, an ordinary code change reuses the 45-second download layer and only re-runs the compile. With COPY . . at the top, every code change downloads every dependency again.
dependency:go-offline is not perfect: Maven resolves some plugin parts only when they run, so the package step may still download a few small files. It still removes almost all of the waiting.
Order of execution
Order the build for fast rebuilds
Tap the lines in the order that keeps the download cached after a code change.
BuildKit cache mount: RUN --mount=type=cache,target=/root/.m2
A cache mount is a folder that BuildKit keeps between builds and attaches only while one RUN runs, written RUN --mount=type=cache,target=/root/.m2 .... Its contents are never saved in a layer, so the image does not grow.
A cache mount keeps the downloaded jars between builds. The Dockerfile below adds one to both Maven steps.
# syntax=docker/dockerfile:1FROM eclipse-temurin:25-jdk AS buildWORKDIR /buildCOPY .mvn/ .mvn/COPY mvnw pom.xml ./RUN --mount=type=cache,target=/root/.m2 ./mvnw -B dependency:go-offlineCOPY src ./srcRUN --mount=type=cache,target=/root/.m2 ./mvnw -B package -DskipTestsExample 3 · A cache mount after changing pom.xml
Runs in: a Spring Boot project folder with Docker installed
# Add spring-boot-starter-mail to pom.xml, then rebuild with full logsdocker build --progress=plain -t shoplite-api:1.2.0 .#8 [build 5/7] RUN --mount=type=cache,target=/root/.m2 ./mvnw -B dependency:go-offline #8 4.902 [INFO] Scanning for projects... #8 6.377 [INFO] Downloading from central: https://repo.maven.apache.org/maven2/org/springframework/boot/spring-boot-starter-mail/4.1.1/spring-boot-starter-mail-4.1.1.pom #8 6.512 [INFO] Downloaded from central: https://repo.maven.apache.org/maven2/org/springframework/boot/spring-boot-starter-mail/4.1.1/spring-boot-starter-mail-4.1.1.pom (2.6 kB at 21 kB/s) ... #8 9.874 [INFO] BUILD SUCCESS #8 DONE 10.3s
What this code does
- The
pom.xmlchange invalidated step 5, so go-offline ran again. Because/root/.m2was mounted from the cache, it downloaded only the new starter and its new dependencies (shortened here with...). - Without the mount the same step would download every dependency again, about 45 seconds for ShopLite. Versions, sizes and speeds will differ for you.
The go-offline layer has one weakness: when pom.xml changes, the layer is rebuilt from scratch and every jar downloads again. With a cache mount on /root/.m2, the rebuilt step finds the old jars already there and downloads only the new dependency. Example 3 adds one starter and the step takes 10 seconds instead of 45.
The first line, # syntax=docker/dockerfile:1, asks BuildKit for the latest stable Dockerfile syntax, which documents that the file uses newer features such as --mount.
docker builder prune deletes it locally.Spring Boot layered jars: java -Djarmode=tools extract --layers
A layered jar is a Spring Boot fat jar that can split itself into folders by how often each part changes: dependencies, spring-boot-loader, snapshot-dependencies and application (your own classes).
First extract the layers on your computer and look at them. Then read the Dockerfile that copies each layer on its own.
Example 4 · Looking at the layers on your computer
Runs in: a Spring Boot 4.1 project folder in a terminal with Java installed
./mvnw -B package -DskipTestsjava -Djarmode=tools -jar target/shoplite-api-1.2.0.jar list-layerscp target/shoplite-api-1.2.0.jar application.jarjava -Djarmode=tools -jar application.jar extract --layers --destination extractedls extracted extracted/application extracted/dependenciesdependencies spring-boot-loader snapshot-dependencies application extracted: application dependencies snapshot-dependencies spring-boot-loader extracted/application: application.jar extracted/dependencies: lib
What this code does
list-layersprints the four layers in order, from the one that changes least to the one that changes most. That is also the order toCOPYthem.extract --layersmakes one folder per layer:dependencies/lib/holds the library jars andapplication/holdsapplication.jarwith your classes.snapshot-dependenciesis empty for ShopLite because it uses no-SNAPSHOTversions.- The jar is copied to
application.jarfirst, because the extracted launcher jar keeps the name of the jar you extract.
Example 5 · The layered Dockerfile for shoplite-api
Runs in: a Spring Boot project folder with Docker installed
# syntax=docker/dockerfile:1FROM eclipse-temurin:25-jdk AS buildWORKDIR /buildCOPY .mvn/ .mvn/COPY mvnw pom.xml ./RUN --mount=type=cache,target=/root/.m2 ./mvnw -B dependency:go-offlineCOPY src ./srcRUN --mount=type=cache,target=/root/.m2 ./mvnw -B package -DskipTestsRUN cp target/*.jar application.jarRUN java -Djarmode=tools -jar application.jar extract --layers --destination extractedFROM eclipse-temurin:25-jreWORKDIR /applicationCOPY --from=build /build/extracted/dependencies/ ./COPY --from=build /build/extracted/spring-boot-loader/ ./COPY --from=build /build/extracted/snapshot-dependencies/ ./COPY --from=build /build/extracted/application/ ./EXPOSE 8080ENTRYPOINT ["java", "-jar", "application.jar"][+] Building 74.9s (20/20) FINISHED docker:desktop-linux ... => [build 9/9] RUN java -Djarmode=tools -jar application.jar extract --layers 1.4s => [stage-1 2/6] WORKDIR /application 0.1s => [stage-1 3/6] COPY --from=build /build/extracted/dependencies/ ./ 0.6s => [stage-1 4/6] COPY --from=build /build/extracted/spring-boot-loader/ ./ 0.0s => [stage-1 5/6] COPY --from=build /build/extracted/snapshot-dependencies/ 0.0s => [stage-1 6/6] COPY --from=build /build/extracted/application/ ./ 0.1s => exporting to image 0.9s => => naming to docker.io/library/shoplite-api:1.2.0 0.0s
What this code does
- The build stage is the multi-stage build from the last lesson plus go-offline, cache mounts, a copy to
application.jarand the extract step. The stage is calledbuild, as in the last lesson; Spring Boot's own docs name itbuilder, but stage names are free labels. - The final stage copies the four folders in order of change frequency into
/application, soapplication.jarandlib/end up side by side. - The first build runs every step; the
dependenciescopy is the slowest final-stage step because it holds tens of megabytes of jars.
java -Djarmode=tools -jar application.jar extract --layers --destination extracted (Spring Boot 3.3 and newer) writes the four folders. A plain fat jar is one 60 MB file, so a one-line code change makes a new 60 MB layer to build, push and pull. With four COPY --from lines a code change touches only the small application layer; the big dependencies layer stays cached and is not uploaded again.
The extracted application.jar is a small jar whose manifest lists the jars in lib/ on its class path, so java -jar application.jar still starts the app. That is why the build first copies the jar to the fixed name application.jar.
-Djarmode=layertools and start the app with java org.springframework.boot.loader.launch.JarLauncher; that is the form from before Spring Boot 3.3. On ShopLite's Spring Boot 4.1.1 use -Djarmode=tools as shown.Reading build output: CACHED vs re-run steps
CACHED at the start of a build-output line means Docker reused the saved layer and spent no time on it. A line without it ran again, and its time on the right shows where the build spends its seconds.
A ShopLite rebuild after a one-line code change: the output shows which steps were reused and which ran again.
Example 6 · Two builds side by side: what CACHED tells you
Runs in: a Spring Boot project folder with Docker installed
# Edit ProductController.java, then rebuild and pushdocker build -t shoplite-api:1.2.0 .[+] Building 24.8s (20/20) FINISHED docker:desktop-linux => [internal] load build context 0.1s => => transferring context: 3.41kB 0.0s => [build 1/9] FROM docker.io/library/eclipse-temurin:25-jdk@sha256:9b1e…c4d2 0.0s => [stage-1 1/6] FROM docker.io/library/eclipse-temurin:25-jre@sha256:4b6f…8abc 0.0s => CACHED [build 2/9] WORKDIR /build 0.0s => CACHED [build 3/9] COPY .mvn/ .mvn/ 0.0s => CACHED [build 4/9] COPY mvnw pom.xml ./ 0.0s => CACHED [build 5/9] RUN --mount=type=cache,target=/root/.m2 ./mvnw -B depen 0.0s => [build 6/9] COPY src ./src 0.1s => [build 7/9] RUN --mount=type=cache,target=/root/.m2 ./mvnw -B package -Ds 21.7s => [build 8/9] RUN cp target/*.jar application.jar 0.3s => [build 9/9] RUN java -Djarmode=tools -jar application.jar extract --layers 1.2s => CACHED [stage-1 2/6] WORKDIR /application 0.0s => CACHED [stage-1 3/6] COPY --from=build /build/extracted/dependencies/ ./ 0.0s => CACHED [stage-1 4/6] COPY --from=build /build/extracted/spring-boot-load 0.0s => CACHED [stage-1 5/6] COPY --from=build /build/extracted/snapshot-depende 0.0s => [stage-1 6/6] COPY --from=build /build/extracted/application/ ./ 0.1s => exporting to image 0.2s
What this code does
- The first non-cached line is
[build 6/9] COPY src ./src: the change entered there, so steps 6 to 9 of the build stage ran. The download step 5 stayedCACHED. - In the final stage,
dependencies,spring-boot-loaderandsnapshot-dependenciesareCACHEDbecause their files did not change; only theapplicationlayer, a few hundred KB, is new. - A
docker pushafter this build uploads only that small layer; the registry already has the rest. BuildKit cuts long step names in this view;--progress=plainshows them in full.
Read a rebuild from top to bottom and find the first step that ran: that is where the change entered. Every later step in the same stage runs as well. In the final stage, a COPY --from is CACHED when the files it copies have the same content as last time, even though the build stage re-ran.
So after a code change the ShopLite rebuild re-runs only COPY src, the compile and the extract, and the final stage writes just the small application layer.
Next step
Check your understanding
12 quick questions