如何在Dockerfile中使用现有的Docker卷
我创造了一个新的docker形象。 它创build一个新的文件夹/hello
。 当我将这个图像作为一个容器运行时,我可以通过docker exec -it
.. bash命令访问容器,当我执行ls
我会看到/hello
文件夹。
这个/hello
文件夹也保存在Docker卷容器中。 所以我已经把容器和现有的Docker卷联系起来了。 所以它是持久的。
现在是我的问题:是否有可能在Dockerfile中执行以下操作?
新图像想要使用与前一个容器相同的卷,并将/hello
文件复制到其自己的容器中。
这可能在docker文件中执行吗?
不,这在Dockerfile
是不可能的。
使用--volumes-from
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 ../
然后在另一个terminal(上面的容器仍在运行):
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
然后在你的原始terminal:
/# 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
而在你的新terminal:
/# 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
只有容器的卷仍在运行时,才能将卷从一个容器链接到另一个容器。