用volume container共享数据-每天5分钟玩转Docker容器技术(42)

每天5分钟Docker (4.1万) 2019-05-09 15:35:03

volume container 是专门为其他容器提供 volume 的容器。它提供的卷可以是 bind mount,也可以是 docker managed volume。下面我们创建一个 volume container:

用volume container共享数据-每天5分钟玩转Docker容器技术(42)_https://www.tiejiang.org_每天5分钟Docker_第1张

我们将容器命名为 vc_data(vc 是 volume container 的缩写)。注意这里执行的是 docker create 命令,这是因为 volume container 的作用只是提供数据,它本身不需要处于运行状态。容器 mount 了两个 volume:

bind mount,存放 web server 的静态文件。

docker managed volume,存放一些实用工具(当然现在是空的,这里只是做个示例)。

通过 docker inspect 可以查看到这两个 volume。

# docker inspect vc_data
......
"Mounts": [
    {
        "Source": "/root/htdocs",
        "Destination": "/usr/local/apache2/htdocs",
        "Mode": "",
        "RW": true,
        "Propagation": "rprivate"
    },
    {
        "Name": "1b603669398d117e499449862636a56c4f4c804d447c680e7b3ba7c7f5e52205",
        "Source": "/var/lib/docker/volumes/1b603669398d117e499449862636a56c4f4c804d447c680e7b3ba7c7f5e52205/_data",
        "Destination": "/other/useful/tools",
        "Driver": "local",
        "Mode": "",
        "RW": true,
        "Propagation": ""
    }
],
......

其他容器可以通过 --volumes-from 使用 vc_data 这个 volume container:

用volume container共享数据-每天5分钟玩转Docker容器技术(42)_https://www.tiejiang.org_每天5分钟Docker_第2张

三个 httpd 容器都使用了 vc_data,看看它们现在都有哪些 volume,以 web1 为例:

# docker inspect web1
......
"Mounts": [
    {
        "Source": "/root/htdocs",
        "Destination": "/usr/local/apache2/htdocs",
        "Mode": "",
        "RW": true,
        "Propagation": "rprivate"
    },
    {
        "Name": "1b603669398d117e499449862636a56c4f4c804d447c680e7b3ba7c7f5e52205",
        "Source": "/var/lib/docker/volumes/1b603669398d117e499449862636a56c4f4c804d447c680e7b3ba7c7f5e52205/_data",
        "Destination": "/other/useful/tools",
        "Driver": "local",
        "Mode": "",
        "RW": true,
        "Propagation": ""
    }
],
......

web1 容器使用的就是 vc_data 的 volume,而且连 mount point 都是一样的。验证一下数据共享的效果:

用volume container共享数据-每天5分钟玩转Docker容器技术(42)_https://www.tiejiang.org_每天5分钟Docker_第3张

可见,三个容器已经成功共享了 volume container 中的 volume。

下面我们讨论一下 volume container 的特点:

与 bind mount 相比,不必为每一个容器指定 host path,所有 path 都在 volume container 中定义好了,容器只需与 volume container 关联,实现了容器与 host 的解耦。

使用 volume container 的容器其 mount point 是一致的,有利于配置的规范和标准化,但也带来一定的局限,使用时需要综合考虑。

另一种在容器之间共享数据的方式是 data-packed volume container,下一节讨论。

THE END

Leave a Reply

用户评论(1)

  • 心灵博客 2019年5月12日 16:24

    不错,从你这学到了不少,前几天我连容器和镜像都有些搞混 😆