Docker 运行 --mount 使所有文件在 运行 期间在不同的文件夹中可用

Docker run --mount make all files available in a different folder during RUN

我想在 RUN 语句期间使主机上的文件夹可用。即类似于容器运行与-v:

的效果
docker run -v /path/on/host:/path/in/container mycontainer:tag

在容器中,这给了我 /path/in/container 以及 path/on/host 中的所有 files/folder。

为此,我正在尝试 https://github.com/moby/buildkit/blob/master/frontend/dockerfile/docs/experimental.md:

中的实验性挂载选项
RUN --mount=type=bind,target=/path/on/host

这在 RUN 期间给了我一个文件夹 /path/on/host

然后我有两个问题:

  1. 我可以在 /path/on/hostls 文件,但不能使用它们(例如 cat 它们)。我尝试将 type 更改为例如cache 并像在 https://devops.stackexchange.com/questions/6078/in-a-dockerfile-is-there-a-way-to-avoid-copying-files-to-make-them-accessible-t 中那样使用 source,但我无法使其工作。

  2. 我不知道如何在“RUN 图像”中设置不同的路径,即 /path/in/container 而不是 /path/on/host

我认为您误解了 RUN --mount=type=bind... 语法的用途。来自文档:

This mount type allows binding directories (read-only) in the context or in an image to the build container.

换句话说,这不允许您在构建阶段访问任意主机目录。它不是 docker run-v 命令行选项的模拟。它只允许您:

  • 从你的构建上下文中挂载目录,或者
  • 从多阶段构建中的另一个阶段装载目录

例如,我可以这样做,将目录从一个构建阶段挂载到后续构建阶段:

# syntax=docker/dockerfile:experimental

FROM centos AS centos

FROM alpine
RUN --mount=type=bind,from=centos,source=/,target=/centos ls /centos > /root/centos.txt

或者如果我的构建上下文中有一个名为 example 的目录,我可以在构建过程中执行此操作来挂载它:

# syntax=docker/dockerfile:experimental

FROM centos AS centos

FROM alpine
RUN --mount=type=bind,source=example,target=/data cp /data/* /root/

您正在使用的语法(未指定 from)...

RUN --mount=type=bind,target=/path/on/host

...只需将构建上下文的根安装到容器内的 /path/on/host 上。请记住,target 指定容器内的挂载点。例如,如果我的构建上下文如下所示:

.
├── Dockerfile
└── example
    └── README.md

并且example/README.md包含:

This is a test.

并且 Dockerfile 包含一个 RUN 选项,类似于您正在使用的选项:

# syntax=docker/dockerfile:experimental

FROM centos AS centos

FROM alpine
RUN --mount=type=bind,target=/data cat /data/example/README.md > /root/README.md

那么在构建镜像的时候,/root/README.md就有了example/README.md的内容。