在宿主机中找一个本地文件系统之上的目录,而后把这一目录直接与,docker容器文件系统之上的目录或文件,建立所谓的绑定关系,类似于硬盘挂载
好处是,容器关闭甚至是删除时,都不用担心数据丢失了
docker 有两种类型的卷
两个容器可以共享同一个本地目录,同时指向就可以了
本地和容器的路径都需要指定进行绑定,有着脱离容器生命周期的数据持久功能
只需在容器中指定挂载卷,在本地中会自动创建,有docker自己维护,路径在docker inspect中可以查看
docker挂载卷
``` [root@localhost ~]# docker run --name b2 -it -v /data busybox / # ls bin data dev etc home proc root sys tmp usr var / # echo "hello worlk" > /data/index.html / # cat /data/index.html hello worlk ```新终端
[root@localhost _data]# docker inspect b2
"Mounts": [
{ "Source":"/var/lib/docker/volumes/2117d576ec10fbcf375af1fe35ff56d6e5b2bffa0db784d9ad664f412d6318f1/_data",
}
],
[root@localhost _data]# cat /var/lib/docker/volumes/2117d576ec10fbcf375af1fe35ff56d6e5b2bffa0db784d9ad664f412d6318f1/_data/index.html
hello worlk
绑定挂载卷
``` [root@localhost ~]# docker run --name b2 -it --rm -v /data/voumes/b2:/data busybox / # ```新终端
[root@localhost _data]# docker inspect b2
"Mounts": [
{
"Type": "bind",
"Source": "/data/voumes/b2",
"Destination": "/data",
}
[root@localhost _data]# echo "<h1>Busybox httpd server.</h1>" > /data/voumes/b2/index.html
[root@localhost _data]# cat /data/voumes/b2/index.html
<h1>Busybox httpd server.</h1>
目录会自动创建
验证数据持久连接,重新创建容器,宿主机路径与容器不同的路径建立关联关系
[root@localhost ~]# docker run --name b2 -it --rm -v /data/voumes/b2:/data busybox
/ # exit
[root@localhost ~]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
bd141921d661 haoran/httpd:v0.2 "/bin/httpd -f -h /d…" 3 days ago Exited (137) 3 days ago t2
162ebb705c34 nginx:1.14-alpine "nginx -g 'daemon of…" 5 days ago Exited (0) 4 days ago web1
[root@localhost ~]# docker run --name b2 -it -v /data/voumes/b2:/data/web busybox
/ # cat /data/web/index.html
<h1>Busybox httpd server.</h1>
复制容器卷设置
复制使用其他容器的卷,为docker run命令使用--volumes-from选项
[root@localhost ~]# docker run --name juanpeizhimoban -it -v /data/infracon/volume/:/data/web/html busybox
/ #
基础底层卷模板镜像可以不运行
[root@localhost ~]# docker inspect -f {{.Mounts}} juanpeizhimoban
[{bind /data/infracon/volume /data/web/html true rprivate}]
[root@localhost ~]# docker inspect -f {{.NetworkSettings.IPAddress}} juanpeizhimoban
10.0.0.2
复制基础底层卷模板镜像
[root@localhost _data]# docker run --name b2 --network container:juanpeizhimoban --volumes-from juanpeizhimoban -it --rm busybox
/ #
[root@localhost ~]# docker inspect b2
"Source": "/data/infracon/volume",
"Destination": "/data/web/html",
/ # ip a
37: eth0@if38: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1500 qdisc noqueue
link/ether 02:42:0a:00:00:02 brd ff:ff:ff:ff:ff:ff
inet 10.0.0.2/16 brd 10.0.255.255 scope global eth0
valid_lft forever preferred_lft forever