无法将Maven依赖项缓存在Docker映像中

问题描述

我正在使用sh文件,其中包含所有maven配置,秘密密钥,maven命令。当我运行容器时,它一次又一次下载依赖项,无法缓存依赖项。

这是我的Dockerfile的样子:

#MVN as build tool
FROM docker.hub.com/maven:3.5.3-jdk-8

#Settings.xml for downloading dependencies from nexus repository
ARG MVN_SETTINGS=settings.xml

#Maven project pom
ARG MVN_POM=pom.xml

#Defining the current working repository
workdir /usr/src/app


#coping the settings.xml into working directory
copY ${MVN_SETTINGS} settings.xml

#coping the pom.xml into working directory
copY ${MVN_POM} pom.xml

#Download the package and make it cached in docker image
RUN mvn -B -f ./pom.xml -s settings.xml dependency:resolve-plugins dependency:resolve


#coping the source code into working repository
copY  src .

copY  Test.sh .

#Execute permission
RUN chmod a+x Test.sh

#Entry point for docker container
CMD ./Test.sh

这是Test.sh文件

#!bin/bash
mvn test -DtestSuite=src/test/resources/suites/Suite.xml

当我创建docker映像并运行容器时,每次运行它都会一次又一次下载依赖项。

解决方法

您想要的东西是不可能的-至少使用“常规” Docker和Dockerfile-有关说明,请参见此question

不过,您可以对RUN语句使用experimental Dockefile syntaxenable caching来达到预期的效果:

# syntax = docker/dockerfile:1.0-experimental
FROM docker.hub.com/maven:3.5.3-jdk-8

ARG MVN_SETTINGS=settings.xml
ARG MVN_POM=pom.xml

WORKDIR /usr/src/app

COPY ${MVN_SETTINGS} settings.xml
COPY ${MVN_POM} pom.xml
RUN --mount=type=cache,target=/root/.m2 mvn -B -f ./pom.xml -s settings.xml dependency:resolve-plugins dependency:resolve

COPY src .
COPY Test.sh .
RUN chmod a+x Test.sh
CMD ./Test.sh

以上Dockerfile将启用/root/.m2目录的缓存。该命令仍将每次运行,但不会重新下载依赖项。就是说,该Dockerfile不适用于“常规” Docker。它需要BuildKit

我还建议您使用BuildX plugin并使用docker buildx build构建映像,以便在构建引擎之间轻松切换而无需设置和取消设置环境变量。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...