docker - 挂载和卷的区别

感觉这方面的知识很乱,我花了点时间,重新梳理了一下。

挂载(mount)

挂载(mount)作为动词使用的时候,就是把容器外的文件,挂载到容器内,容器所使用的文件,实际用的是宿主机的文件。

挂载的概念,并不局限于 docker,宿主机也会用到挂载,像是挂载 “云盘”、“硬盘”、“虚拟存储”、“其它主机的文件或文件夹” 等。

除此之外,还有 nfs 挂载这种东西。

挂载(bind mounts)和卷(volumes)

绑定挂载(bind mounts)和卷(volumes)是两个不同的名词。

二者并没有太多区别,都是将容器外的文件,挂载到容器内部。

卷的特殊之处在于,它受到 docker 的管理,可以把卷理解成:有文件管理系统的文件夹。

日常交流过程中,可能非常混乱,有时候会把 “绑定挂载” 叫做 “卷”,也有可能会把 “卷” 称作 “挂载”,强调区别的时候,可以说 “挂载普通文件夹” 和 “挂载卷”。

映射

很多人会把 “挂载” 解释为 “映射”,这种说法不大对,因为,在官网文档中,你甚至看不到 “映射” 这个词。

使用 “映射” 这个词,容易联想到数据备份,让人产生一个错觉:认为数据是从容器内部映射出来的,容器内部一份,卷里也有一份。

实际情况是,数据会直接存放在挂载的文件夹中,不会产生复数的文件。

容器产生 10G 的文件,占用的磁盘就是 10G,不存在映射这个过程,不会变成 20G。

映射可能是因为习惯,就像 RequestMapping,路径指向文件资源。

卷的优势

提一个最简单一个需求:

docker 部署了很多应用,需要清除没用的卷,这时候可能过去很久了,你已经记不清挂载了多少文件夹,如果是你用的是卷,就有命令可以直接用。

基本语法

# 创建卷
docker volume create [my-vol]

# 移除卷
docker volume rm [my-vol]

# 查看卷
docker volume inspect [my-vol]

# 移除无用的卷
docker volume prune

# 卷的存储路径,迁移数据时重点关注内容
# /var/lib/docker/volumes

# 样例,使用卷创建容器
docker run -d --name=nginxtest -v nginx-vol:/usr/share/nginx/html nginx:latest
# 样例,设置卷只允许读,共享卷的时候可能会被用到
docker run -d --name=nginxtest -v nginx-vol:/usr/share/nginx/html:ro nginx:latest

绑定挂载与卷的区别

从官方文档的说法上看,绑定挂载的历史比卷更久,卷可能后期优化产生的,因为卷受到 docker 管理,有了很多管理功能。

If you bind-mount a directory into a non-empty directory on the container, the directory's existing contents are
obscured by the bind mount.
这是官方强调的区别:挂载到容器内非空目录的时候,挂载会掩盖现有内容。

另外就是像是系统环境参数这些,这时候用卷就不方便了,例如:etc/localtime。

绑定挂载定义(官网)

https://docs.docker.com/storage/bind-mounts/

Bind mounts have been around since the early days of Docker. Bind mounts have limited functionality compared to volumes.
When you use a bind mount, a file or directory on the host machine is mounted into a container. The file or directory is
referenced by its absolute path on the host machine. By contrast, when you use a volume, a new directory is created
within Docker's storage directory on the host machine, and Docker manages that directory's contents.

绑定挂载在Docker的早期就已经存在了。与卷相比,绑定挂载的功能有限。 使用绑定挂载时,将主机上的文件或目录挂载到容器中。文件或目录由其在主机上的绝对路径引用。
相比之下,当您使用卷时,在主机上的Docker存储目录中创建一个新目录,并且Docker管理该目录的内容。

卷定义(官网)

https://docs.docker.com/storage/volumes/

Volumes are the preferred mechanism for persisting data generated by and used by Docker containers. While bind mounts
are dependent on the directory structure and OS of the host machine, volumes are completely managed by Docker.

卷是持久化 docker 数据(由 docker 生成和使用的数据)的首选机制。 绑定挂载依赖于主机的目录结构和操作系统,而卷完全由Docker管理。

In addition, volumes are often a better choice than persisting data in a container's writable layer, because a volume
doesn't increase the size of the containers using it, and the volume's contents exist outside the lifecycle of a given
container.

此外,卷通常是比在容器的可写层中持久化数据更好的选择,因为卷不会增加使用它的容器的大小, 并且卷的内容存在于给定容器的生命周期之外。

posted on 2023-09-11 17:03  疯狂的妞妞  阅读(171)  评论(0编辑  收藏  举报

导航