(四)如何共享資料?
資料共享是 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,下節討論,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/228756.html
標籤:其他
上一篇:什么是集群、分布式和微服務?
