How do you cache Maven/Gradle/Go modules without bloating the image?
IntermediateProductionBuild Performance & CI
Answer
Use cache mounts, not layers:
RUN --mount=type=cache,target=/root/.m2 mvn -B -DskipTests package
RUN --mount=type=cache,target=/go/pkg/mod --mount=type=cache,target=/root/.cache/go-build go build ./...
Because the cache lives outside layers, nothing is added to the image and it survives builder restarts as long as the builder volume does.
More on Build Performance & CI
How do you make Docker builds fast in CI where runners are ephemeral?BeginnerWhat are the cache backends in buildx?BeginnerWhy does `inline` cache often disappoint?AdvancedHow do you structure a Python Dockerfile for the best caching and size?IntermediateHow do you structure a Node.js production image?IntermediateHow do you build a small Java image?Beginner