目的:1、宿主机或容器间共享数据2、数据的持久化
方法:数据卷、数据卷容器
表现为,共享目录
数据卷
docker run -v创建绑定挂载点
-v|--volume[=[[HOST-DIR:]CONTAINER-DIR[:OPTIONS]]]
Create a bind mount.
If you specify, -v /HOST-DIR:/CONTAINER-DIR, 指定了宿主机挂载点,会绑定指定目录
Docker bind mounts /HOST-DIR in the host to /CONTAINER-DIR in the Docker container.
If 'HOST-DIR' is omitted,
Docker automatically creates the new volume on the host. 不指定宿主机挂载点,会在宿主机自动创建一个目录
The OPTIONS are a comma delimited list and can be:
· [rw|ro]
· [z|Z]
· [[r]shared|[r]slave|[r]private]
· [delegated|cached|consistent]
· [nocopy]
举例:
指定宿主机挂载点
宿主机在共享目录中新建一个文件file1,写入内容
[root@localhost ~]# echo "host" >convol/file1
在容器中查看
[root@localhost ~]# docker exec -it d3e69264be7b cat /vol-1/file1
host
在容器中更新file1,在宿主机中查看
[root@localhost ~]# docker exec -it d3e69264be7b /bin/bash
[root@d3e69264be7b /]# ls
bin dev etc home lib lib64 lost+found media mnt opt proc root run sbin srv sys tmp usr var vol-1
[root@d3e69264be7b /]# cd vol-1/
[root@d3e69264be7b vol-1]# ls
file1
[root@d3e69264be7b vol-1]# echo "container" >> file1
[root@d3e69264be7b vol-1]# read escape sequence
[root@localhost ~]# cat convol/file1
host
container
docker inspect查看
关闭容器后,再启动容器,会重新挂载上
容器只读权限设置
[root@localhost ~]# docker run -it -v /root/convol/:/vol-2:ro centos
docker inspect查看
不指定宿主机挂载点
[root@localhost ~]# docker run -it -v vol-3 centos
[root@3fa6d202af32 /]# ls
bin dev etc home lib lib64 lost+found media mnt opt proc root run sbin srv sys tmp usr var vol-3
[root@3fa6d202af32 /]# [root@localhost ~]#
dockerfile
docker中添加VOLUME属性
VOLUME["/dataVolumeContainer","/dataVolumeContainer2","/dataVolumeContainer3"]
编辑dockerfile文件
docker build根据dockerfile文件生成镜像
[root@localhost docker]# docker build -f /docker/dockerfile -t hjc/centos
运行容器
docker inspect查看
写入一个文件查看
数据卷容器
命名的容器挂载数据卷,其它容器通过挂载这个(父容器)实现数据共享,挂载数据卷的容器,称之为数据卷容器
--volumes-from=[]
Mount volumes from the specified container(s) 从指定的容器挂载卷
Mounts already mounted volumes from a source container onto another
container. You must supply the source's container-id. To share 必须指定源容器的ID
a volume, use the --volumes-from option when running 使用--volumes-from参数,容器间共享卷
the target container. You can share volumes even if the source container 源容器未运行也可以共享
is not running.
By default, Docker mounts the volumes in the same mode (read-write or 默认docker挂载卷的权限和源卷相同
read-only) as it is mounted in the source container. Optionally, you
can change this by suffixing the container-id with either the :ro or 可以修改挂载权限
:rw keyword.
If the location of the volume from the source container overlaps with 如果容器上已经有了相同名字的卷,共享卷会隐藏容器上的卷
data residing on a target container, then the volume hides
that data on the target.
创建一个带数据卷的容器host1
创建容器host2,使用--volumes-from参数
docker inspect查看属性
可以看到,共享的目录相同