docker build with maven – how to prevent re-downloading dependencies

I want the base image mavenDeps to download the dependencies and rebuild only when dependencies change, and the second image, mavenBuild to rebuild on code changes. However, on docker build . both maven commands download all dependencies. I might be misunderstanding how the stacking works or what to copy where.

What I have tried: explicitly copying everything from first container to second: COPY / / and various more specific COPY targets like .m2, building second container from the maven base image, like the first one, then copying everything from the first container.


FROM maven:3.5-jdk-8 as mavenDeps
COPY pom.xml pom.xml
RUN mvn dependency:resolve

FROM mavenDeps as mavenBuild
RUN mvn install

FROM java:8
COPY --from=mavenBuild ./target/*.jar ./
CMD [ "bash", "-c", "java ${JAVA_OPTS} -jar *.jar -v"]

I am building with Docker Desktop (engine 19.03.5) on MacOS.

EDIT 2020.03.04:

Answer from @gcallea effectively prevents re-downloading of dependencies listed in the pom file +1. However, the install step still pulls 100+ artifacts on each build triggered by a code change. Those are transient dependencies of maven-resources-plugin, maven-compiler-plugin and several other plugins which are not listed anywhere explicitly.

I need to work offline sometimes and would like to preload ALL dependencies, so no dependencies are pulled after code changes.

Source: StackOverflow