在docker中,volume的意思是“数据卷”,可以绕过默认的联合文件系统,以正常的文件或者目录的形式存在于宿主机上,进而实现保存持久化数据以及共享容器间的数据。

本教程操作环境:linux7.3系统、docker-1.13.1版、Dell G3电脑。
docker中volume是什么意思
Docker Volume,通常翻译为数据卷,用于保存持久化数据。当我们将数据库例如MySQL运行在Docker容器中时,一般将数据通过Docker Volume保存在主机上,这样即使删除MySQL容器,数据依然保存在主机上,有效保证了数据的安全性。
1. 指定Docker Volume
使用docker run命令,可以运行一个Docker容器
docker run -itd --volume /tmp/data1:/tmp/data2 --name test ubuntu bash
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.txt
ls /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.txt
docker exec test ls /tmp/data2/
hello.txt
world.txt
world.txt文件在主机/tmp/data1/目录中可见
ls /tmp/data1/
hell
.........................................................