容器数据卷挂载实现

容器的启动运用到了 OverlayFS,而容器的数据持久化就需要用到数据卷,数据卷的实现就不是使用 OverlayFS 了,Docker 提供了四种挂载类型的实现:

  • Volume mounts
  • Bind mounts
  • tmpfs mounts
  • Named pipes

Volume mounts

Volume mounts 是 Docker 管理的一块独立存储,保存在宿主机的特定目录中,默认是 /var/lib/docker/volumes/,用于数据持久化,常用于数据库等场景。

创建一个测试用的容器:

1
docker run -d --name nginx -v data:/data harbor.warnerchen.com/library/nginx:mainline

查看容器具体信息,就可以发现类型为 volume

1
2
3
4
5
6
7
8
9
10
11
12
13
root@docker-rancher:~# docker inspect nginx | jq .[0].Mounts
[
{
"Type": "volume",
"Name": "data",
"Source": "/var/lib/docker/volumes/data/_data",
"Destination": "/data",
"Driver": "local",
"Mode": "z",
"RW": true,
"Propagation": ""
}
]

查看 volume

1
2
3
4
5
6
7
8
9
10
11
12
13
14
root@docker-rancher:~# docker volume ls | grep data
local data
root@docker-rancher:~# docker volume inspect data
[
{
"CreatedAt": "2025-06-04T15:26:49+08:00",
"Driver": "local",
"Labels": null,
"Mountpoint": "/var/lib/docker/volumes/data/_data",
"Name": "data",
"Options": null,
"Scope": "local"
}
]

Bind mounts

Bind mounts 是将宿主机上的一个具体路径挂载到容器中,方便开发和调试,宿主机上的文件变化会立即同步进容器中。

1
docker run -d --name nginx -v $(pwd)/data:/data harbor.warnerchen.com/library/nginx:mainline

查看挂载信息:

1
2
3
4
5
6
7
8
9
10
11
root@docker-rancher:~# docker inspect nginx | jq .[0].Mounts
[
{
"Type": "bind",
"Source": "/root/data",
"Destination": "/data",
"Mode": "",
"RW": true,
"Propagation": "rprivate"
}
]

Tmpfs mounts

Tmpfs mounts 是将容器内某目录挂载到宿主机内存中,但不落盘,适合保存临时数据,如敏感信息或高频读写缓存。

1
docker run -d --name nginx --tmpfs /app/tmp harbor.warnerchen.com/library/nginx:mainline

查看挂载信息:

1
2
3
4
root@docker-rancher:~# docker inspect nginx | jq .[0].HostConfig.Tmpfs
{
"/app/tmp": ""
}

Named pipes

Named pipes 是挂载宿主机上的命名管道(FIFO)或 Unix socket 文件到容器中,用于宿主机与容器之间的进程通信(IPC),如 Docker CLI 与 Docker 守护进程通信。

1
docker run -v /var/run/docker.sock:/var/run/docker.sock harbor.warnerchen.com/library/nginx:mainline
Author

Warner Chen

Posted on

2025-06-04

Updated on

2025-06-04

Licensed under

You need to set install_url to use ShareThis. Please set it in _config.yml.
You forgot to set the business or currency_code for Paypal. Please set it in _config.yml.

Comments

You forgot to set the shortname for Disqus. Please set it in _config.yml.