数据卷

数据卷核心作用:用来实现容器与宿主机之间数据共享

数据卷是一个可供一个或多个容器使用的特殊目录,它绕过 UFS,可以提供很多有用的特性

  • 数据卷 可以在容器之间共享和重用
  • 数据卷 的修改会立马生效
  • 数据卷 的更新,不会影响镜像
  • 数据卷 默认会一直存在,即使容器被删除

注意:数据卷 的使用,类似于 Linux 下对目录或文件进行 mount,镜像中的被指定为挂载点的目录中的文件会复制到数据卷中(仅数据卷为空时会复制)。

数据卷操作:

  • 自定义数据卷目录:docker run -v 绝对路径:容器内路径
  • 自动创建数据卷:docker run -v 卷名:容器内路径

Docker数据卷常用命令

1. 创建数据卷

  • docker volume create 数据卷名

    1
    2
    [root@localhost ~]# docker volume create info
    info

2. 查看数据卷

  • 查看当前所有的数据卷:docker volume ls

    1
    2
    3
    4
    [root@localhost ~]# docker volume ls
    DRIVER VOLUME NAME
    local 585aa47ef49e47b7980c29f91d74288bb3aa51bbcf9882157d357d890f9154bd
    local info
  • 查看数据卷细节:docker volume inspect 数据卷名

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    [root@localhost ~]# docker volume inspect info
    [
    {
    "CreatedAt": "2021-02-10T23:08:33+08:00",
    "Driver": "local",
    "Labels": {},
    "Mountpoint": "/var/lib/docker/volumes/info/_data",
    "Name": "info",
    "Options": {},
    "Scope": "local"
    }
    ]

3. 挂载数据卷

  • docker run -v 宿主机的路径|任意别名:/容器内的路径 镜像名
  • docker run -v 宿主机的路径|任意别名:/容器内的路径:ro 镜像名 ro代表容器内部的目录只读

注:docker运行容器时,添加参数-v进行数据卷挂载

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
[root@localhost ~]# docker run -d -P --name web -v info:/usr/share/nginx/html nginx
86b1f7b8b93a9d326bcea2e03beeb8038211db7dd010dda77d9cb48cebd9559a
[root@localhost ~]# docker inspect web
[
{
……
"Mounts": [
{
"Type": "volume",
"Name": "info",
"Source": "/var/lib/docker/volumes/info/_data",
"Destination": "/usr/share/nginx/html",
"Driver": "local",
"Mode": "z",
"RW": true,
"Propagation": ""
}
],
……
}
]

4. 删除数据卷

  • 删除没有使用的数据卷:docker volume prune
  • 删除指定的数据卷:docker volume rm 数据卷名