Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I cache Maven dependencies and plugins in a Docker Multi Stage Build Layer?

I want to cache Maven dependencies in a layer of the build stage of my Docker Multi Stage Build.

My Dockerfile looks as follows:

FROM maven:3-jdk-8 as mvnbuild
RUN mkdir -p /opt/workspace
WORKDIR /opt/workspace
COPY pom.xml .
RUN mvn -B -s /usr/share/maven/ref/settings-docker.xml dependency:resolve
COPY . .
RUN mvn -B -s /usr/share/maven/ref/settings-docker.xml package

FROM openjdk:8-jre-alpine
...

```

I based this Dockerfile on the example provided in the Docker Multi Stage Build blog post (also available on Github).

When I run the build, instead of seeing the dependencies downloaded once by dependency:resolve and then re-used by package, I am seeing the dependencies downloaded by both steps.

Has anyone got this working? What am I doing wrong here?

like image 715
Trastle Avatar asked Dec 25 '17 14:12

Trastle


1 Answers

I'd like to offer my two cents on this one.

I started with this Dockerfile:

FROM maven:3-jdk-10 AS build

RUN mkdir /src
WORKDIR /src
COPY pom.xml .
RUN mvn -B dependency:resolve-plugins dependency:resolve

COPY . .
RUN mvn package

The goal is to not have any dependencies downloaded during the build step (which is mvn package).

I tried to add the clean package trick that is mentioned in the answer by @Apolozeus but this does not have an effect. In my case, I have surefire being downloaded during test and a mapstruct plugin being downloaded during compilation.

What I did in the end is to explicitly add these two plugins in my pom.xml so that they will be downloaded early on:

    <dependency>
        <groupId>org.apache.maven.surefire</groupId>
        <artifactId>surefire-junit4</artifactId>
        <version>2.21.0</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.mapstruct</groupId>
        <artifactId>mapstruct-processor</artifactId>
        <version>1.2.0.Final</version>
        <scope>compile</scope>
    </dependency>

This works and no further downloads happen during the build step, which speeds up the build.

like image 187
Nikolaos Georgiou Avatar answered Sep 20 '22 09:09

Nikolaos Georgiou