如何在 Docker 文件中使用现有的 Docker 卷
How to use existing Docker Volume in a Dockerfile
我创建了一个新的 docker 图片。它会创建一个新文件夹 /hello
。
当我 运行 这个图像作为容器时,我可以通过 docker exec -it
.. bash 命令访问容器,当我执行 ls
我看到 /hello
文件夹。
此 /hello
文件夹也保存在 Docker 卷容器中。
因此,我已将容器与现有的 Docker 卷相关联。所以很执着。
现在我的问题是:是否可以在 Docker 文件中执行以下操作?
一个新镜像想使用与之前容器相同的卷,并将/hello
文件复制到它自己的容器中。
这可以在 docker 文件中执行吗?
不,这在您的 Dockerfile
中是不可能的。
当您 运行 另一个具有 docker run
的容器时,您可以通过使用 --volumes-from
参数来使用 运行ning 容器卷。
示例:
Docker 文件
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 ../
然后在另一个终端(上面的容器仍然是运行ning):
Docker 文件
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
您只能 link 卷从一个容器到另一个容器,而带有卷的容器仍然是 运行ning。
我创建了一个新的 docker 图片。它会创建一个新文件夹 /hello
。
当我 运行 这个图像作为容器时,我可以通过 docker exec -it
.. bash 命令访问容器,当我执行 ls
我看到 /hello
文件夹。
此 /hello
文件夹也保存在 Docker 卷容器中。
因此,我已将容器与现有的 Docker 卷相关联。所以很执着。
现在我的问题是:是否可以在 Docker 文件中执行以下操作?
一个新镜像想使用与之前容器相同的卷,并将/hello
文件复制到它自己的容器中。
这可以在 docker 文件中执行吗?
不,这在您的 Dockerfile
中是不可能的。
当您 运行 另一个具有 docker run
的容器时,您可以通过使用 --volumes-from
参数来使用 运行ning 容器卷。
示例:
Docker 文件
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 ../
然后在另一个终端(上面的容器仍然是运行ning):
Docker 文件
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
您只能 link 卷从一个容器到另一个容器,而带有卷的容器仍然是 运行ning。