一、定义
数据卷是一个可供一个或多个容器使用的特殊目录,它绕过 UFS,可以提供很多有用的特性:
数据卷可以在容器之间共享和重用
对数据卷的修改会立马生效
对数据卷的更新,不会影响镜像
卷会一直存在,直到没有容器使用
*数据卷的使用,类似于 Linux 下对目录或文件进行 mount。
1、数据卷将宿主机中的目录与指定容器内的目录进行挂载
2、数据卷容器
容器之间进行挂载,实现文件系统之间通讯但是此种方案无法实现容器之间直接的网络通讯
二、创建数据卷
//宿主机目录/var/www挂载容器中的/data1
docker run -volume /var/www:/data1 --name web1 -it centos /bin/bash
简写成
docker run -v /var/www:/data1 --name web1 -it centos /bin/bash
[root@localhost ~]# docker run -itv /var/www:/data1 --name centos03 centos:7 /bin/bash
没有的文件夹都会被建立
容器目录
宿主机目录
[root@localhost ~]# cd /var
[root@localhost var]# cd www
[root@localhost www]# ls
在容器里data1目录下新建一个文件
[root@0c8d366331c7 /]# touch /data1/index.html
[root@0c8d366331c7 /]# ls /data1
index.html
在宿主机中对文件添加内容
[root@localhost www]# echo "this is a test" > index.html
然后在容器里查看内容
[root@0c8d366331c7 /]# cat /data1/index.html 内容已添加
this is a test
退出容器
[root@0c8d366331c7 /]# exit
exit
但宿主机中内容还在
[root@localhost www]# cat index.html
this is a test
应用场景:
原理:将容器内部的配置文件目录,挂载到宿主机指定目录下作用:
修改配置文件例如,nginx.conf /usr/local/nginx/conf/nginx.conf —>/container_nginx/ conf / nginx.conf
容器内部产生的日志,如何收集
将容器内部存方日志文件的目录挂载到宿主机指定目录下/container nginx/log/access_log/access_log
传入变量挂载到宿主机在宿主机上添加变量内容,将变量放入共享目录,在容器中/etc/profile"直接加载就可以export xxdir=/data/ data1/xx.
三、数据卷容器
多个容器之间实现数据挂载,持久化到本机
//数据卷容器
docker run -it --name web100 -v /data1 -v /data2 centos /bin/bash
命名 暴露2个挂载点
//新容器挂载数据卷容器web100
docker run -it --volumes-from web100 --name db1 centos /bin/bash
从哪个容器读取挂载 新容器命名
[root@localhost ~]# docker run -it --name centos01 -v data1 -v data2 centos:7 /bin/bash
[root@localhost ~]# docker run -it --volumes-from centos01 --name centos02 centos:7 /bin/bash
[root@36b92407d427 /]# echo "text01" > /data1/1.txt
[root@36b92407d427 /]# echo "text02" > /data2/2.txt
在挂载文件夹里查看
[root@5dea7e3ced22 /]# cat /data1/1.txt
text01
[root@5dea7e3ced22 /]# cat /data2/2.txt
text02
四、容器互联:
使用自定义配置启动redis
[root@localhost ~]# mkdir -p /data/redis
[root@localhost ~]# cd /data/redis/
[root@localhost redis]# ls
[root@localhost redis]# echo "appendonly yes" >> /data/redis/redis.conf
[root@localhost redis]# ls
redis.conf
[root@localhost redis]# pwd
/data/redis
[root@localhost redis]# docker run -v /data/redis/redis.conf:/etc/redis/redis.conf \
> -v /data/redis/data:/data \
> -d --name myredis \
> -p 6379:6379 \
> redis:latest redis-server /etc/redis/redis.conf
启动redisdeskupmanger软件
##配置账号密码
[root@localhost redis]# echo "requirepass abc123" >>/data/redis/redis.conf
[root@localhost redis]# cat redis.conf
appendonly yes
requirepass abc123