玩转Docker系列5】Docker数据存储

网友投稿 589 2022-05-29

1 docker数据存储

【玩转Docker系列5】Docker数据存储

1.1  数据卷

1.1.1 容器内创建数据卷

数据卷是在一个或多个容器,它绕过Union File System的一个专门指定的目录。数据卷的目的是持久化数据,独立于容器的生命周期。Docker因此不会自动删除卷,当你删除一个容器,也不会“垃圾回收”直到没有容器再使用。

在docker run时加上-v参数来添加一个数据卷,-v参数也可以使用多次,以挂载多个数据卷。

UbuntuTest:~   # docker run -it --name data_volume -v /test ubuntu:14.04   /bin/bash

root@0800180dc5be:/#   ls -l /test

drwxr-xr-x     2 root root 4096 Sep 20 11:00 test

root@0800180dc5be:/#   cd /test/

root@0800180dc5be:/test#   touch test.volume

root@0800180dc5be:/test#   ls

test.volume

root@0800180dc5be:/test#   exit

exit

UbuntuTest:~   # docker start data_volume

data_volume

UbuntuTest:~   # docker attach data_volume

root@0800180dc5be:/#

root@0800180dc5be:/#   ls -l /test/

total 0

-rw-r--r--   1 root root 0 Sep 20 11:01 test.volume

1.1.2     主机目录作为数据卷

挂载主机目录为数据卷,必须参照-v hostPATH:containerPATH这种格式,路径必须为绝对路径,以保证容器的可移植性。

该功能支持主机目录和文件作为容器的数据卷。本文3.2.3章节在容器中安装软件时需要从主机通过命令拷贝软件,部分容器不支持scp功能时还无法拷贝,利用该功能实现方式更简单而不用关注容器是否支持远程拷贝命令。

UbuntuTest:~ # docker run -it --name data_host_container -v /root:/tmp/root   ubuntu:14.04 /bin/bash

root@2bda024d88d5:/#   ls -l /tmp/root/

total 1571632

-rw-r--r--  1   root root    148899 Sep  7 10:41   CloudServiceTestTools.tgz

root@2bda024d88d5:/#   touch /tmp/root/container_data.test

root@2bda024d88d5:/#   exit

exit

UbuntuTest:~ # ls -l   container_data.test

-rw-r--r-- 1 root   root 0 Sep 20 19:12 container_data.test

1.2    数据卷容器

如果你有一些持续更新的数据需要在容器之间共享,最好创建数据卷容器。 数据卷容器,其实就是一个正常的容器,专门用来提供数据卷供其它容器挂载的。

步骤1:创建数据卷容器db_volume,其共享目录为/dbdata

UbuntuTest:~ # docker run -it -d -v   /dbdata --name db_volume ubuntu:14.04   /bin/bash

97aab02e3d582e585f40b92d711869598313eeb4d6b24d595985f192609de412

UbuntuTest:~ # docker   ps -l

CONTAINER   ID     IMAGE       COMMAND     CREATED        STATUS     PORTS         NAMES

97aab02e3d58      ubuntu:14.04   "/bin/bash"    11 seconds   ago  Up 10   seconds                db_volume

步骤2:其它容器挂载数据卷容器db_volume的数据卷

UbuntuTest:~ # docker run -it --name db_1 --volumes-from   db_volume ubuntu:14.04 /bin/bash

root@4123dfc817d2:/#   echo "This is file of db_1" > /dbdata/db_1_file.log

root@4123dfc817d2:/#   ls -l /dbdata/

total 4

-rw-r--r-- 1 root   root 21 Sep 20 11:29 db_1_file.log

步骤3:容器db_1、db_2可同时读写数据卷

UbuntuTest:~ # docker run -it --name db_2 --volumes-from   db_volume ubuntu:14.04 /bin/bash

root@7d399ccbe79e:/#   cat /dbdata/db_1_file.log

This is file of db_1

转载请注明出处:华为云博客 https://portal.hwclouds.com/blogs

Docker

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:《数字政府云原生基础设施白皮书》发布!
下一篇:智慧屏 + WeLink = ?
相关文章