与主机的容器共享目录或卷

时间:2015-10-06 07:27:01

标签: docker share

我有一个目录(可能是以后的卷),我想与我的所有交互式容器共享。我知道,原生Docker卷存储在/var/lib/docker/volumes下,而docker run -v似乎是最简单的方法,但我认为Data Volume Container是一种更加标准化的方式。我不知道如何从目录或现有的另一个卷创建此卷容器。也许这是错误的方法?

2 个答案:

答案 0 :(得分:4)

There are two ways to create and share volumes: 1. using the VOLUME instruction on the Dockerfile. 2 Specifying the -v <volume_name> option during container runtime and later using --volumes-from=<container> with every subsequent container which need to share the data. Here is an ex with the later:

  1. Start your first container with -v, then add a test file under the directory of the shared volume.
docker run -it -v /test-volume --name=testimage1 ubuntu:14.04 /bin/bash

root@ca30f0f99401:/# ls
bin  boot  dev  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  test-volume ===> test-volume dir got created here

root@ca30f0f99401:/# touch test-volume/1

root@ca30f0f99401:/# cat > test-volume/1     
Test Message!
  1. From the host OS, you can get details of the volume by inspecting your container:

docker inspect ca30f0f99401 | grep -i --color -E '^|Vol'

"Mounts": 
        {
            "Name": "025835b8b47d282ec5f27c53b3165aee83ecdb626dc36b3b18b2e128595d9134",
            "Source": "/var/lib/docker/volumes/025835b8b47d282ec5f27c53b3165aee83ecdb626dc36b3b18b2e128595d9134/_data",
            "Destination": "/test-volume",
            "Driver": "local",
            "Mode": "",
            "RW": true 

"Image": "ubuntu:14.04",
    "Volumes": {
        "/test-volume": {} }
  1. Start another container with a shared volume and check if the shared folder/files exists.
$ docker run -it --name=testimage2 --volumes-from=testimage1 ubuntu:14.04 /bin/bash

root@60ff1dcebc44:/# ls 
bin  boot  dev  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  test-volume  tmp  usr  var

root@60ff1dcebc44:/# cat test-volume/1
Test Message!
  1. Goto step-3 to share volume with a new container.

答案 1 :(得分:2)

通过编写一个专用的Dockerfile来创建一个数据卷容器:

  • COPY您的文件夹
  • 将复制的本地容器路径文件夹声明为VOLUME

然后docker create <imagename>,您获得({3}}一个(已创建的)容器,前提是您使用--volumes-from <containername>选项运行它们。