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:

The two rules below fix one problem each.

1. Each step is cached, and a change reruns that step and every step after it. Docker reuses a step's earlier result if its inputs are unchanged. For 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
2. Order steps from rarely changed to often changed. "Try to make expensive steps appear near the beginning of the Dockerfile. Steps that change often should appear near the end." For Java, copy 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.

3. Build in one stage, ship from another. A Dockerfile can have several 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
4. The runtime stage needs a JRE, not a JDK. 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
5. Keep junk out of the context with .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
Going further, not required. Docker's official Java guide uses this same shape and adds 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.
Kubernetes will…

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.

Related ideas