Docker for Kubernetes · Lesson 3 · About 30 minutes
Smaller, faster builds: the build cache and multi-stage
By the end, your Java service will build with Maven inside Docker. A code change will rebuild without downloading anything, and the image you ship will have no compiler, no Maven and no source code in it.
Warm-up
From memory first. Retrieving something days after you learned it is what makes it last.
Two problems with the Lesson 2 approach
Real Java services are built with Maven or Gradle, not with a bare javac. The obvious first try puts the whole project in a Maven image and runs the build:
FROM maven:3.9-eclipse-temurin-21
WORKDIR /app
COPY . .
RUN mvn -B package
EXPOSE 8080
CMD ["java", "-jar", "target/app.jar"]
It works, but when we tested it:
- It's slow to iterate. After a one-word change to
App.java, the rebuild downloaded 157 files from Maven Central again. That's every plugin Maven needs, and it happens on every code change. - It's big and full of build tools. The image is 590 MB. It ships Maven, the full JDK with its compiler, your source code and Maven's download folder, none of which a running service needs.
The two rules below fix one problem each.
COPY, the inputs are the files' contents. "If a layer changes, all other layers that come after it are also affected." In the file above, COPY . . sees your edit, so RUN mvn -B package starts from nothing again and downloads everything.
Docker Docs: Docker build cache
pom.xml by itself, download the dependencies, and only then copy src. Editing code invalidates COPY src and later steps; the expensive download step stays cached until you change pom.xml.
Docker Docs: Optimize cache usage
Try it: what reruns?
Here is the naive Dockerfile. Predict, then check.
FROM lines, and each starts a new stage. Name one with FROM … AS build, then copy a file out of it with COPY --from=build. "You can selectively copy artifacts from one stage to another, leaving behind everything you don't want in the final image." The image you get is only the last stage.
Docker Docs: Multi-stage builds
eclipse-temurin:21-jre can run a jar but has no javac. Maven and the JDK stay in the build stage. The Temurin docs go further with a custom runtime built by jlink, which is a later step, not needed now.
Eclipse Temurin image docs
.dockerignore.
Put it "in the root of your build context." It works "similarly to .gitignore" and is meant for "temporary files, log files, and build artifacts". For Maven that means target/, which a local mvn package fills, and .git. Otherwise, every build sends those files to the builder.
Docker Docs: Keep the context small
Write it yourself
Put all five rules into one Dockerfile. You get one hint at a time; your draft is saved in this browser.
Predict the cache, again
This is the multi-stage file. Notice that the two stages are cached separately.
Build it on your machine
In your docker-lab folder, make a Maven project. The service is the one from Lesson 2, now in package hello:
mkdir -p hello-maven/src/main/java/hello && cd hello-maven
# hello-maven/
# pom.xml
# .dockerignore
# Dockerfile.naive ← the naive file at the top of this lesson
# Dockerfile ← your checked multi-stage file
# src/main/java/hello/App.java
src/main/java/hello/App.java is Lesson 2's code with package hello; as its first line. .dockerignore has two lines, target/ and .git. The pom.xml has no dependencies; it only names the jar app.jar and sets its main class:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<groupId>hello</groupId>
<artifactId>hello</artifactId>
<version>0.2</version>
<properties>
<maven.compiler.release>21</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<finalName>app</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.4.2</version>
<configuration>
<archive><manifest><mainClass>hello.App</mainClass></manifest></archive>
</configuration>
</plugin>
</plugins>
</build>
</project>
1. Feel the problem
docker build -t dk-hello:naive -f Dockerfile.naive .
# now change "Hello from" to "Hi from" in App.java, then:
docker build --progress=plain -t dk-hello:naive -f Dockerfile.naive . | grep -c "Downloaded from"
# about 157: every plugin, downloaded again
--progress=plain prints every line of build output instead of the compact view, so you can search it.
2. Fix it
docker build -t dk-hello:0.2 . # the first build downloads everything once, so it's slow
# change the greeting again, then:
docker build --progress=plain -t dk-hello:0.2 . | grep -E "CACHED|Downloaded from"
# CACHED lines for COPY pom.xml and go-offline, no downloads
docker images dk-hello # 0.1: 502MB naive: 590MB 0.2: 341MB
3. Confirm what shipped
docker run -d --name dk-hello -p 8080:8080 dk-hello:0.2
curl localhost:8080 # Hi from 6c1f… (give the JVM a few seconds)
docker exec dk-hello ls /app # app.jar, and nothing else
docker exec dk-hello javac -version # fails: no compiler in a JRE image
docker history dk-hello:0.2 # your layers: WORKDIR, then COPY app.jar (a few kB)
Most of the 341 MB is the JRE base image, which your other Java images will share layer by layer (Lesson 1). Your own layer is the jar, a few kilobytes. Clean up, keeping dk-hello:0.2 for Lesson 4:
docker rm -f dk-hello
docker rmi dk-hello:naive dk-hello:shell dk-hello:0.1
RUN --mount=type=cache,target=/root/.m2, which keeps Maven's download folder between builds even when pom.xml changes. Cache mounts need BuildKit; we'll come back to them if your builds get slow.- pull your image onto each node before it can start a Pod there. With the default
IfNotPresentpolicy, "the image is pulled only if it is not already present locally" (Kubernetes: Images). A smaller image starts faster on a new node, and an unchanged JRE base layer is already there, so only the jar layer moves. - never build anything. The cluster only gets the last stage. Maven, the JDK and your source code never reach it, so a running Pod has fewer tools an attacker could use.
Check yourself
From memory, without scrolling up.
Keep going
Read next: Docker's Multi-stage builds (short), then Optimize cache usage, the sections on ordering layers and keeping the context small.
Keep for review: the Dockerfile cheat sheet, now with the multi-stage Java template; the Docker CLI cheat sheet; and the glossary, with stage, build cache and .dockerignore added.
Ask your teacher: if anything is unclear, ask in the chat, however small. Gradle instead of Maven? Ask about that too. When you finish, send both quiz scores, the questions you missed, and the download counts and sizes from your machine.