【问题标题】:How to use existing Docker Volume in a Dockerfile如何在 Dockerfile 中使用现有的 Docker Volume
【发布时间】:2016-01-18 08:34:27
【问题描述】:

我创建了一个新的 docker 镜像。它会创建一个新文件夹/hello。 当我将此映像作为容器运行时,我可以通过 docker exec -it .. bash 命令访问该容器,当我执行 ls 时,我会看到 /hello 文件夹。

/hello 文件夹也保存在 Docker 卷容器中。 所以我已经将容器与现有的 Docker 卷链接起来。所以它是持久的。

现在是我的问题:是否可以在 Dockerfile 中执行以下操作?

一个新镜像想要使用与前一个容器相同的卷,并将/hello 文件复制到它自己的容器中。

这可以在 docker 文件中执行吗?

【问题讨论】:

  • 我不完全理解这个问题。通常使用 -v 选项将卷附加到容器。为此,您的 Dockerfile 中不需要任何特殊内容。您能否提供有关该问题的更多信息?

标签: docker docker-volume


【解决方案1】:

不,这在您的 Dockerfile 中是不可能的。

当您使用docker run 运行另一个容器时,您可以使用--volumes-from 参数来使用正在运行的容器卷。

例子:

Dockerfile

FROM ubuntu:14.04

VOLUME /hello

然后:

$ docker build -t test-image-with-volume .
$ docker run -ti --name test-image-with-volume test-image-with-volume bash
/# cd /hello
/# ls -la
total 8

drwxr-xr-x  2 root root 4096 Jan 18 14:59 ./
drwxr-xr-x 22 root root 4096 Jan 18 14:59 ../

然后在另一个终端中(上面的容器仍在运行):

Dockerfile

FROM ubuntu:14.04

然后:

$ docker build -t test-image-without-volume .
$ docker run -ti test-image-without-volume bash
/# cd /hello
bash: cd: /hello: No such file or directory
/# exit
$ docker run -ti --volumes-from test-image-with-volume test-image-without-volume bash
/# cd /hello
total 8

drwxr-xr-x  2 root root 4096 Jan 18 14:59 ./
drwxr-xr-x 22 root root 4096 Jan 18 14:59 ../
/# touch test

然后在你原来的终端中:

/# ls -la /hello
total 8

drwxr-xr-x  2 root root 4096 Jan 18 15:04 .
drwxr-xr-x 22 root root 4096 Jan 18 15:03 ..
-rw-r--r--  1 root root    0 Jan 18 15:04 test

在您的新终端中:

/# ls -la /hello
total 8

drwxr-xr-x  2 root root 4096 Jan 18 15:04 .
drwxr-xr-x 22 root root 4096 Jan 18 15:03 ..
-rw-r--r--  1 root root    0 Jan 18 15:04 test

您只能在包含卷的容器仍在运行时将卷从一个容器链接到另一个容器。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-06
    • 1970-01-01
    • 1970-01-01
    • 2016-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多