This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

Maven Docker cache dependencies

I am trying to automate Maven builds using Docker. The project I was building took nearly 20 minutes to download all the dependencies, so I tried to build a Docker image that could cache them, but didn’t seem to save it. My Dockerfile is

FROM maven:alpine
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
ADD pom.xml /usr/src/app
RUN mvn dependency:go-offline
Copy the code

The image is built and everything is actually downloaded. However, the generated image looks the same size as the base Maven: Alpine image, so it does not appear that the dependencies are cached in the image. When I tried MVN compilation with images, it took me 20 minutes to re-download everything.

Can I build a Maven image that caches my dependencies so I don’t have to download them every time I use them for a build?

I am running the following command:

docker build -t my-maven .

docker run -it --rm --name my-maven-project -v "$PWD":/usr/src/mymaven -w /usr/src/mymaven my-maven mvn compile
Copy the code

My understanding is that anything RUN does during the Docker build becomes part of the resulting image.

Answer 1:

Typically, pom.xml when you try to start a Docker image build, nothing changes in the file, only some other source code changes. In this case, you can do the following:

FROM maven:3-jdk-8

ENV HOME=/home/usr/app

RUN mkdir -p $HOME

WORKDIR $HOME

# 1. add pom.xml only here

ADD pom.xml $HOME

# 2. start downloading dependencies

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

# 3. add all source code and start compiling

ADD . $HOME

RUN ["mvn", "package"]

EXPOSE 8005

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

So the key is:

1. Add the pom.xml file.

2, then MVN Verify –fail-never, which will download the Maven dependencies.

3, then add all the source files, then start compiling (MVN package).

When there are changes in the pom.xml file or the first time you run this script, Docker will execute 1-> 2->3. When nothing changes in the pom.xml file, Docker skips steps 1 and 2 and goes straight to 3.