什么是Docker Volume?

摘要Docker Volume,通常翻译为数据卷,用于保存持久化数据。当我们将数据库例如MySQL运行在Docker容器中时,一般将数据通过Docker Volume保存在主机上,这样即使删除MySQL容器,数据依然保存在主机上,有效保证了数据的安全性。这篇博客将通过简单的实践帮助大家理解什么是Docker Volume
[![]

img_f683126dae41279d62d2212750ec89ac.jpe
docker_volume.jpg

本文所有命令都是在play-with-docker的在线Docker实例上执行,Docker版本为17.05.0-ce
1. 指定Docker Volume
使用docker run命令,可以运行一个Docker容器
docker run -itd --volume /tmp/data1:/tmp/data2 --name test ubuntu bash

基于ubuntu镜像创建了一个Docker容器。
容器的名称为test,由--name选项指定。
Docker Volume--volume选项指定,主机的/tmp/data1目录与容器中的/tmp/data2目录一一对应。

2. 查看Docker Volume
使用docker inspect命令,可以查看Docker容器的详细信息:
docker inspect --format='{{json .Mounts}}' test | python -m json.tool[ { "Destination": "/tmp/data2", "Mode": "", "Propagation": "", "RW": true, "Source": "/tmp/data1", "Type": "bind" }]

使用--format选项,可以选择性查看需要的容器信息。.Mount为容器的Docker Volume信息。
python -m json.tool可以将输出的json字符串格式化显示。
Source表示主机上的目录,即/tmp/data1
Destination为容器中的目录,即/tmp/data2

3. 本机文件可以同步到容器
在本机/tmp/data1目录中新建hello.txt文件
touch /tmp/data1/hello.txtls /tmp/data1/hello.txt

hello.txt文件在容器/tmp/data2/目录中可见
使用docker exec命令,可以在容器中执行命令。
docker exec test ls /tmp/data2/hello.txt

可知,在本机目录/tmp/data1/的修改,可以同步到容器目录/tmp/data2/中。
4. 容器文件可以同步到主机
在容器/tmp/data2目录中新建world.txt文件
docker exec test touch /tmp/data2/world.txtdocker exec test ls /tmp/data2/hello.txtworld.txt

world.txt文件在主机/tmp/data1/目录中可见
ls /tmp/data1/hello.txt world.txt

可知,在容器目录/tmp/data2/的修改,可以同步到主机目录/tmp/data1/中。
5. 结论
Docker Volume本质上是容器与主机之间共享的目录或者文件,这样Docker Volume中的数据可以在主机和容器中实时同步。使用Virtualbox创建虚拟机时,也可以配置共享目录,这与Docker Volume非常相似。
欢迎加入我们FundebugDocker技术交流群: 305097057

img_9d47844bc7e2fe4b7b0d2ddf608fce98.jpe

版权声明:
转载时请注明作者 Fundebug以及本文地址:**
https://blog.fundebug.com/2017/06/07/what-is-docker-volume/**

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值