1、 什么是数据卷
Docker将运用与运行的环境打包形成容器运行 ,运行可以伴随着容器,但是我们对数据的要求是持久化的。
容器之间希望可以共享数据。
Docker容器产生的数据,如果不通过docker commit生成新的镜像,使得数据做为镜像的一部分保存下来, 那么当容器删除后,数据自然也就没有了,为了能保存数据在docker中,我们使用卷。
有点类似我们Redis里面的rdb和aof文件;或者配置中心;再或者k8s里的数据卷。
2、什么时候使用数据卷
- 容器的持久化
- 容器间继承+共享数据
卷就是目录或文件,存在于一个或多个容器中,由docker挂载到容器,但不属于联合文件系统,因此能够绕过Union File System提供一些用于持续存储或共享数据的特性:
卷的设计目的就是数据的持久化,完全独立于容器的生存周期,因此Docker不会在容器删除时删除其挂载的数据卷
特点:
- 数据卷可在容器之间共享或重用数据
- 卷中的更改可以直接生效
- 数据卷中的更改不会包含在镜像的更新中
- 数据卷的生命周期一直持续到没有容器使用它为止
3、 数据卷
3.1在启动容器时添加
https://blog.csdn.net/d495435207/article/details/125069855
命令:docker run -it -v /宿主机绝对路径目录:/容器内目录:[权限] 镜像名
[权限]:ro/rw(只读/读写)
通过在容器内路径后加上ro、rw来改变读写权限
ro readonly # 只读
rw readwrite # 可读可写
默认rw, 如果为ro,这个路径只能通过宿主机来操作,容器内部无法操作
- 新建一个容器:
[root@VM-16-8-centos ~]# docker run -it -v /tmp:/tmp/test ubuntu bash
root@ae9c3272e8d2:/#
【注意观察命令行的“头”的变化】
- 在主机/tmp目录下,新建命令:touch hello.txt
[root@VM-16-8-centos ~]# cd /tmp/
[root@VM-16-8-centos tmp]# touch hello.txt
[root@VM-16-8-centos tmp]# ll
total 1
-rw-r--r-- 1 root root 0 Jun 9 17:03 hello.txt
- 在容器当前目录下执行命令:观察ing
root@ae9c3272e8d2:/# tail -f /tmp/test/hello.txt
- 在主机/tmp目录下,新建命令:
[root@VM-16-8-centos tmp]# echo 你是一个大宝贝呀!华子哥 >> hello.txt
- 观察容器内是否有输出
root@ae9c3272e8d2:/# tail -f /tmp/test/hello.txt
你是一个大宝贝呀!华子哥
3.2 查看容器的挂载卷
命令:docker inspect 容器id
(描述非常长,截取关注的部分)
[root@VM-16-8-centos tmp]# docker inspect ae9c3272e8d2
"Mounts": [
{
"Type": "bind",
"Source": "/tmp",
"Destination": "/tmp/test",
"Mode": "",
"RW": true,
"Propagation": "rprivate"
}
],
3.3 容器之间数据共享
思路:部署两个容器[redis-01,redis-02],将配置文件和数据目录通过主机目录挂载到容器,redis-01 设置一个值并查询设置结果,redis-02查询redis-01设置的值。
宿主机创建目录和配置文件:
[root@VM-16-8-centos docker]# ll
total 96
-rw-r--r-- 1 root root 93756 Jun 15 22:13 redis.conf
drwxr-xr-x 3 systemd-coredump root 4096 Jun 15 22:10 redisdata
[root@VM-16-8-centos docker]# pwd
/data/docker
redis-01 启动并设置值
[root@VM-16-8-centos docker]# docker run -d --name redis-01 -v /data/docker/redisdata:/data -v /data/docker/redis.conf:/etc/redis.conf -p6378:6378 redis redis-server /etc/redis.conf --appendonly yes
5ece31eb393e0c3c6c2096f58c13ae1703a1bc757b483b6dea3a43f68674ccf6
[root@VM-16-8-centos docker]# /usr/local/redis/bin/redis-cli -p 6378 -a naruto_redis_1012
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
127.0.0.1:6378> scan 0
1) "0"
2) (empty array)
127.0.0.1:6378> set huazige hansome
OK
127.0.0.1:6378> get huazige
"hansome"
redis-02 启动并查询redis-01设置的值
[root@VM-16-8-centos docker]# docker run -d --name redis-02 -v /data/docker/redisdata:/data -v /data/docker/redis.conf:/etc/redis.conf -p6377:6378 redis redis-server /etc/redis.conf --appendonly yes
28ca1d860bc0cb8af46bb81d2aaaa1454b85d23a1c6909680550139d272d1d30
[root@VM-16-8-centos docker]# /usr/local/redis/bin/redis-cli -p 6377 -a naruto_redis_1012
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
127.0.0.1:6377> scan 0
1) "0"
2) 1) "huazige"
127.0.0.1:6377> get huazige
"hansome"