无法将Maven依赖项缓存在Docker映像中 [英] Unable to cache maven dependency in docker image

查看:195
本文介绍了无法将Maven依赖项缓存在Docker映像中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using the sh file which contains all the maven configuration, secret keys, maven command. when I run the container it downloads the dependency again and again everytime, it is unable to cache the dependency.

这是我的Dockerfile的样子:

Here is how my Dockerfile looks like :

#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文件

Here is the Test.sh file

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

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

When I create the docker image and run the container it downloads the dependency, again and again, every time I run it.

推荐答案

您想要的是不可能的-至少使用常规 Docker和Dockerfile-请参阅此问题

What you want is not possible - at least using "regular" Docker and Dockerfile - see this question for an explanation.

不过,您可以使用实验Dockefile语法启用 RUN 语句的缓存

You can however achieve the desired effect using an experimental Dockefile syntax to enable caching for RUN statement:

# 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不适用于常规的Dockerfile。码头工人它需要 BuildKit

The above Dockerfile will enable caching of /root/.m2 directory. The command will still run every time, but the dependencies will not be redownloaded. That said, this Dockerfile will not work with "regular" Docker. It requires BuildKit.

我还建议使用 BuildX插件,并使用<$ c构建映像$ c> docker buildx build 允许在构建引擎之间轻松切换,而无需设置和取消设置环境变量。

I would also recommend using BuildX plugin and building the image with docker buildx build to allow for easy switching between build engines without setting and unsetting an environmental variable.

这篇关于无法将Maven依赖项缓存在Docker映像中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆