Maven docker cache dependencies

Usually, there’s no change in pom.xml file but just some other source code changes when you’re attempting to start docker image build. In such circumstance you can do this:


FROM maven:3-jdk-8

ENV HOME=/home/usr/app

RUN mkdir -p $HOME


# 1. add pom.xml only here

ADD pom.xml $HOME

# 2. start downloading dependencies

RUN ["/usr/local/bin/", "mvn", "verify", "clean", "--fail-never"]

# 3. add all source code and start compiling


RUN ["mvn", "package"]


CMD ["java", "-jar", "./target/dist.jar"]

So the key is:

  1. add pom.xml file.

  2. then mvn verify --fail-never it, it will download maven dependencies.

  3. add all your source file then, and start your compilation(mvn package).

When there are changes in your pom.xml file or you are running this script for the first time, docker will do 1 -> 2 -> 3. When there are no changes in pom.xml file, docker will skip step 1、2 and do 3 directly.

This simple trick can be used in many other package management circumstances(gradle、yarn、npm、pip).


You should also consider using mvn dependency:resolve or mvn dependency:go-offline accordingly as other comments & answers suggest.

Leave a Comment