分享

容器(六)如何共享数据?【36】

 小仙女本仙人 2022-09-22 发布于北京

(四)如何共享数据?

数据共享是 volume 的关键特性,本节我们详细讨论通过 volume 如何在容器与 host 之间,容器与容器之间共享数据。

(1)容器与 host 共享数据

我们有两种类型的 data volume,它们均可实现在容器与 host 之间共享数据,但方式有所区别。对于 bind mount 是非常明确的:直接将要共享的目录 mount 到容器。具体请参考前面 httpd 的例子,不再赘述。

docker managed volume 就要麻烦点。由于 volume 位于 host 中的目录,是在容器启动时才生成,所以需要将共享数据拷贝到 volume 中。请看下面的例子:

root@cuiyongchao:~# docker run -d -p 85:80 -v /usr/local/apache2/htdocs/ httpd
196644fbfd1c93cbad5bfcfce6f05b2ad4645cbe455c50c66609631b0d299472

root@cuiyongchao:~# docker cp /root/htdocs/index.html 196644fbfd1c:/usr/local/apache2/htdocs
root@cuiyongchao:~# curl 10.0.0.20:85
321
root@cuiyongchao:~# cat /root/htdocs/index.html
321
root@cuiyongchao:~# 


docker cp 可以在容器和 host 之间拷贝数据,当然我们也可以直接通过 Linux 的 cp 命令复制到 /var/lib/docker/volumes/xxx。

(2)容器之间共享数据

​ 第一种方法是将共享数据放在 bind mount 中,然后将其 mount 到多个容器。还是以 httpd 为例,不过这次的场景复杂些,我们要创建由三个 httpd 容器组成的 web server 集群,它们使用相同的 html 文件,操作如下:

1.将 $HOME/htdocs mount 到三个 httpd 容器。

root@cuiyongchao:~# docker run --name web1 -d -p 80 -v /root/htdocs/:/usr/local/apache2/htdocs httpd
70b7cbf68d1b03c6d35148383f00dc635ec6ef2c9ec140268ae1c9778aab9959
root@cuiyongchao:~# docker run --name web2 -d -p 80 -v /root/htdocs/:/usr/local/apache2/htdocs httpd
9cba816a7b440b4352cca3500c8b2ad6ad55e2250ea0387294abdaedf0499b1c
root@cuiyongchao:~# docker run --name web3 -d -p 80 -v /root/htdocs/:/usr/local/apache2/htdocs httpd
3f69a2f33edfa13d1b30a00827ab21313a9e890c4ce15bafc6e6c51e8189edab

2.查看当前主页内容。

root@cuiyongchao:~# docker ps
CONTAINER ID        IMAGE               COMMAND              CREATED              STATUS              PORTS                   NAMES
3f69a2f33edf        httpd               "httpd-foreground"   12 seconds ago       Up 10 seconds       0.0.0.0:32772->80/tcp   web3
9cba816a7b44        httpd               "httpd-foreground"   18 seconds ago       Up 17 seconds       0.0.0.0:32771->80/tcp   web2
70b7cbf68d1b        httpd               "httpd-foreground"   25 seconds ago       Up 24 seconds       0.0.0.0:32770->80/tcp   web1
root@cuiyongchao:~# curl 10.0.0.20:32770
321
root@cuiyongchao:~# curl 10.0.0.20:32771
321
root@cuiyongchao:~# curl 10.0.0.20:32772
321

3.修改 volume 中的主页文件,再次查看并确认所有容器都使用了新的主页。

root@cuiyongchao:~# echo "this is changing volume."> /root/htdocs/index.html 
root@cuiyongchao:~# 
root@cuiyongchao:~# 
root@cuiyongchao:~# curl 10.0.0.20:32770
this is changing volume.
root@cuiyongchao:~# curl 10.0.0.20:32771
this is changing volume.
root@cuiyongchao:~# curl 10.0.0.20:32772
this is changing volume.
root@cuiyongchao:~# 

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

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多