在使用Docker构建Maven项目时,如何解决减少Maven下载依赖时间的问题?

在使用Docker构建Maven项目时,如何解决减少Maven下载依赖时间的问题?

问题描述:

我已经将常见的mavne依赖关系构建为基本的docker映像,但是当我构建项目Dockerfile时,它仍然会下载依赖项,这将花费很长时间来构建.

I have built common mavne dependencies as a base docker image, but when I build a project Dockerfile, it still will download dependencies which will take a long time to build.

合并下线 maven-dependency-plugin docker多阶段构建的maven脱机模式 >.

Combine go-offline goal of maven-dependency-plugin, maven's offline mode with docker multistage builds.

引用Dockerfile可能是:

# Step : Test and package
FROM maven:3.5.3-jdk-8-alpine as builder
WORKDIR /build
COPY pom.xml .
RUN mvn dependency:go-offline

COPY src/ /build/src/
# -o flag will instruct maven to build on offline mode
RUN mvn -o package

# Step : Package image
FROM openjdk:8-jre-alpine
EXPOSE 4567
CMD exec java $JAVA_OPTS -jar /app/my-app.jar
COPY --from=builder /build/target/*jar-with-dependencies.jar /app/my-app.jar

调用dependency:go-offline将在容器的本地存储库中获取所需的工件.多亏了docker层缓存,这一步将被缓存,因此在新的构建尝试中将被跳过.

Invoking dependency:go-offline will fetch required artifacts on container's local repository. Thanks to docker layer caching, this step will be cached so it will be skipped in a new build attempt.

重要的一点是,复制pom.xml应该先复制源代码,因为pom.xml上的更改必须触发新的Maven工件,因为项目的依赖关系可能已更改.

An important note is that copying pom.xml should precede source code copying as a change on pom.xml must trigger a new pull of maven artifacts as project's dependencies may have changed.

参考

编辑:请注意,根据您的pom.xml,您可能会遇到,该问题未从go-offline目标 中获取,因此导致构建失败.解决方法是,您可以尝试罗曼的答案.

Note that depending on your pom.xml, you may face an open Maven Dependency plugin issue on which some dependencies are not fetched from go-offline goal as they should, resulting in build failure. As a workaround, you can try Romain's answer.