如何在dockerfile中使用cp命令



我想减少我的Dockerfile中使用的层数。因此,我想将COPY命令合并到RUN cp中。

  • 依赖性
    • folder1
    • file1
    • file2
  • Dockerfile

下面的命令工作,我想使用单个RUN cp命令

COPY ./dependencies/file1 /root/.m2
COPY ./dependencies/file2 /root/.sbt/
COPY ./dependencies/folder1 /root/.ivy2/cache

下面的命令说没有这样的文件或目录存在错误。我哪里做错了?

RUN cp ./dependencies/file1 /root/.m2 && 
cp ./dependencies/file2 /root/.sbt/ && 
cp ./dependencies/folder1 /root/.ivy2/cache

你不能那样做。

COPY从主机复制到映像。

RUN cp从图像中的一个位置复制到图像中的另一个位置。

要将其全部放入单个COPY语句中,可以在主机上创建所需的文件结构,然后使用tar将其变为单个文件。然后,当您COPYADD该tar文件时,Docker将解压缩它并将文件放在正确的位置。但是根据您的文件在主机上的当前结构,不可能在单个COPY命令中完成。

问题

COPY用于将文件从主机复制到容器。所以,当你运行

COPY ./dependencies/file1 /root/.m2
COPY ./dependencies/file2 /root/.sbt/
COPY ./dependencies/folder1 /root/.ivy2/cache

Docker会在你的主机上查找file1,file2folder1.

但是,当您使用RUN时,命令将在容器中执行。,并且./dependencies/file1(等等)在您的容器中还不存在,这会导致file not found错误。

简而言之,COPYRUN是不可互换的。


如何修复

如果您不想使用多个COPY命令,您可以使用一个COPY将所有文件从您的主机复制到您的容器,然后使用RUN命令将它们移动到适当的位置。

为了避免复制不必要的文件,使用。dockerignore。例如:

.dockerignore

./dependencies/no-need-file
./dependencies/no-need-directory/

Dockerfile

COPY ./dependencies/ /root/
RUN mv ./dependencies/file1 /root/.m2 && 
mv ./dependencies/file2 /root/.sbt/ && 
mv ./dependencies/folder1 /root/.ivy2/cache

您在/root/.ivy2/cache/中缺少最后一个斜杠

最新更新