本文主要是介绍Docker基础篇4:管理应用程序数据(管理卷及绑定挂载),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Docker提供三种不同的方式将数据从宿主机挂载到容器中:volumes,bind mounts和tmpfs。
(1)volumes:Docker管理宿主机文件系统的一部分(/var/lib/docker/volumes)。
(2)bind mounts:可以存储在宿主机系统的任意位置。
(3)tmpfs:挂载存储在宿主机系统的内存中,而不会写入宿主机的文件系统。
其中前两个管理卷和绑定挂载点经常使用。
1、管理卷volume
管理卷volume官方详细说明:https://docs.docker.com/storage/volumes/
1.1、创建卷
创建卷的路径都在/var/lib/docker/volumes目录下
#创建卷的命令
[root@aliyun205 ~]# docker volume create --help
Usage: docker volume create [OPTIONS] [VOLUME]
Create a volume
Options:-d, --driver string Specify volume driver name (default "local")--label list Set metadata for a volume-o, --opt map Set driver specific options (default map[])
创建一个卷nginx-vol
#创建一个卷nginx-vol
[root@aliyun205 ~]# docker volume create nginx-vol
nginx-vol
[root@aliyun205 ~]# docker volume ls
DRIVER VOLUME NAME
local nginx-vol
#查看卷的详细信息
[root@aliyun205 ~]# docker volume inspect nginx-vol
[{"CreatedAt": "2018-11-30T16:16:14+08:00","Driver": "local","Labels": {},"Mountpoint": "/var/lib/docker/volumes/nginx-vol/_data","Name": "nginx-vol","Options": {},"Scope": "local"}
]
注意,我们发现创建卷的文件路径是/var/lib/docker/volumes/nginx-vol/_data。
1.2、用卷创建一个容器
[root@aliyun205 ~]# docker run -d -it --name=nginx-text --mount src=nginx-vol,dst=/usr/share/nginx/html nginx
e480c78bd7a6cbe4d3e772d318bcf64bdb27c956cafe94a000e6c1331d873fbf
#推荐使用--mount的方式创建卷
[root@aliyun205 ~]# docker run -d -it --name=nginx-test2 -v nginx-vol:/usr/share/nginx/html nginx
1.3、清理删除卷
#停止容器
[root@aliyun205 ~]# docker container stop nginx-test3
nginx-test3
#删除容器
[root@aliyun205 ~]# docker container rm nginx-test3
#删除容器的卷
nginx-test3
[root@aliyun205 ~]# docker volume rm nginx-vol
【总结】
(1)如果没有指定卷,会自动创建;
(2)官方推荐使用--mount,因为更通用。
2、绑定挂载点bind mount
绑定挂载官方参考:官方文档:https://docs.docker.com/engine/admin/volumes/bind-mounts/#start-a-container-with-a-bind-mount
【创建挂载】
[root@aliyun205 ~]# mkdir -p /opt/www
[root@aliyun205 ~]# docker run -d -it --name=nginx03 --mount type=bind,src=/opt/www,dst=/usr/share/nginx/html nginx
486079f4dbdfb34662aab8d2e87db1a8bf9441558636b597f1ad5ac56528fbb0
#在容器外面创建一个文件
[root@aliyun205 ~]# echo "hello">/opt/www/1.html
#进入容器里面查看是否有
[root@aliyun205 ~]# docker exect -it nginx03 bash
root@486079f4dbdf:/# ls /usr/share/nginx/html
1.html
【校验检查挂载】
[root@aliyun205 ~]# docker container inspect nginx03"Mounts": [{"Type": "bind","Source": "/opt/www","Destination": "/usr/share/nginx/html","Mode": "","RW": true,"Propagation": "rprivate"}],
#进入容器里面查看
[root@aliyun205 ~]# docker exec -it nginx03 bash
root@486079f4dbdf:/# mount
/dev/vda1 on /usr/share/nginx/html type ext4 (rw,relatime,data=ordered)
【清理删除挂载】
[root@aliyun205 ~]# docker container stop nginx03
nginx03
[root@aliyun205 ~]# docker container rm nginx03
nginx03
【总结】
(1)如果源文件文件/目录没有存在,不会自动创建,会报错;
(2)如果挂载目录在容器中非空目录,则该目录现有内容将被隐藏。
这篇关于Docker基础篇4:管理应用程序数据(管理卷及绑定挂载)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!