Chapter 3 Docker 数据管理
本次Docker学习基于Datawhale开源地址:https://github.com/datawhalechina/team-learning-program/tree/master/Docker
学习目的
-了解并操作数据卷
-挂载主机目录作为数据卷
一、数据卷
数据卷是一个可供一个或多个容器使用的特殊目录。
-
数据卷可以在容器之间共享和重用
-
对数据卷的修改会立马生效
-
对数据卷的更新,不会影响镜像
-
数据卷默认会一直存在,即使容器被删除
1、创建一个数据卷
$ docker volume create datawhale
datawhale
查看所有的数据卷
$ docker volume ls
DRIVER VOLUME NAME
local datawhale
查看指定数据卷信息
$ docker volume inspect datawhale
[
{
"CreatedAt": "2021-04-16T23:04:06+08:00",
"Driver": "local",
"Labels": {},
"Mountpoint": "/var/lib/docker/volumes/datawhale/_data",
"Name": "datawhale",
"Options": {},
"Scope": "local"
}
]
2、启动一个挂载数据卷的容器
在用 docker run
命令的时候,使用 --mount
标记来将数据卷挂载到容器里。
创建一个名为 web
的容器,并加载一个数据卷到容器的 /usr/share/nginx/html
目录。
$ docker run -d -P \
--name web \
--mount source=datawhale,target=/usr/share/nginx/html \
nginx:alpine
Digest: sha256:07ab71a2c8e4ecb19a5a5abcfb3a4f175946c001c8af288b1aa766d67b0d05d2
Status: Downloaded newer image for nginx:alpine
39d9724a0d0ad21fbc6e048092675b3a819dbc38c78e68b3d3001983012fb234
3、查看数据卷的具体信息
在主机里使用以下命令可以查看 web
容器的信息
$ docker inspect web
数据卷
信息在 “Mounts” Key 下面
"Mounts": [
{
"Type": "volume",
"Name": "datawhale",
"Source": "/var/lib/docker/volumes/datawhale/_data",
"Destination": "/usr/share/nginx/html",
"Driver": "local",
"Mode": "z",
"RW": true,
"Propagation": ""
}
],
4、删除数据卷
$ docker volume rm datawhale
Error response from daemon: remove datawhale: volume is in use - [39d9724a0d0ad21fbc6e048092675b3a819dbc38c78e68b3d3001983012fb234]
由于数据卷在使用,此时无法删除数据卷。Docker 不会在容器被删除后自动删除 数据卷。如果需要在删除容器的同时移除数据卷,可以在删除容器的时候使用 docker rm -v
这个命令。
无主的数据卷可能会占据很多空间,要清理请使用以下命令
$ docker volume prune
WARNING! This will remove all local volumes not used by at least one container.
Are you sure you want to continue? [y/N] Y
Total reclaimed space: 0B
二、挂载主机目录
1、挂载主机目录作为数据卷
使用 --mount
标记可以指定挂载一个本地主机的目录到容器中去。这个功能在进行测试的时候十分方便,比如用户可以放置一些程序到本地目录中,来查看容器是否正常工作。
$ docker run -d -P \
--name web \
--mount type=bind,source=/src/webapp,target=/usr/share/nginx/html \
nginx:alpine
上面的命令加载主机的 /src/webapp
目录到容器的 /usr/share/nginx/html
目录。本地目录的路径必须是绝对路径。加了 readonly
之后,就挂载为 只读
了。
$ docker run -d -P \
--name web \
--mount type=bind,source=/src/webapp,target=/usr/share/nginx/html,readonly \
nginx:alpine
如果你在容器内 /usr/share/nginx/html
目录新建文件,会显示如下错误
/usr/share/nginx/html
touch: new.txt: Read-only file system
2、查看数据卷的具体信息
在主机里使用以下命令可以查看 web
容器的信息
$ docker inspect web
挂载主机目录
的配置信息在 “Mounts” Key 下面
"Mounts": [
{
"Type": "bind",
"Source": "/src/webapp",
"Destination": "/usr/share/nginx/html",
"Mode": "",
"RW": true,
"Propagation": "rprivate"
}
],
3、挂载一个本地主机文件作为数据卷
--mount
标记也可以从主机挂载单个文件到容器中
$ docker run --rm -it \
--mount type=bind,source=$HOME/.bash_history,target=/root/.bash_history \
ubuntu:18.04 \
bash
总结
-数据卷方便多个容器共享数据,减少空间占用。
-如果挂载一个空的数据卷到容器中的一个非空目录中,那么这个目录下的文件会被复制到数据卷中。
-如果挂载一个非空的数据卷到容器中的一个目录中,那么容器中的目录会显示数据卷中的数据。