Video in progress
How does the Docker build cache work, and why is pom.xml copied separately before the source code?
Every instruction is its own layer, and Docker takes it from the cache if nothing has changed. When one layer changes, everything after it is rebuilt, so things that rarely change (dependencies) should come first.
📖 Answer
The slow version:
COPY . .
RUN ./mvnw package -DskipTests # downloads the whole internet every time
You change one Java file, so the COPY . . layer changes, the next RUN runs again, and Maven pulls every dependency once more. The build takes 5 minutes instead of 30 seconds.
The faster version:
COPY .mvn/ .mvn/
COPY mvnw pom.xml ./
RUN ./mvnw dependency:go-offline -B # if pom is unchanged: from cache
COPY src/ src/
RUN ./mvnw package -DskipTests -B
Now when the code changes, only the last two layers are rebuilt. pom.xml changes rarely, so the dependency layer is almost always in the cache.
With BuildKit there is an even better way: RUN --mount=type=cache,target=/root/.m2 ./mvnw package. It keeps the Maven repo between builds, so even if pom.xml changes, it does not download everything again. Whether the cache survives in CI depends on the runner setup, so check that separately.
Sign up to mark studied questions and save your progress.