容器(六)如何共享數據?【36】

(四)如何共享數據?

數據共享是 volume 的關鍵特性,本節咱們詳細討論經過 volume 如何在容器與 host 之間,容器與容器之間共享數據。html

(1)容器與 host 共享數據

咱們有兩種類型的 data volume,它們都可實如今容器與 host 之間共享數據,但方式有所區別。對於 bind mount 是很是明確的:直接將要共享的目錄 mount 到容器。具體請參考前面 httpd 的例子,再也不贅述。web

docker managed volume 就要麻煩點。因爲 volume 位於 host 中的目錄,是在容器啓動時才生成,因此須要將共享數據拷貝到 volume 中。請看下面的例子:docker

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。apache

(2)容器之間共享數據

​ 第一種方法是將共享數據放在 bind mount 中,而後將其 mount 到多個容器。仍是以 httpd 爲例,不過此次的場景複雜些,咱們要建立由三個 httpd 容器組成的 web server 集羣,它們使用相同的 html 文件,操做以下:curl

1.將 $HOME/htdocs mount 到三個 httpd 容器。tcp

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.查看當前主頁內容。ui

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 中的主頁文件,再次查看並確認全部容器都使用了新的主頁。this

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,下節討論。url

相關文章
相關標籤/搜索