docker 容器数据卷是容器在运行过程中持久化数据的一种方式,卷是目录或文件,存在于一个或多个容器中,由docker 挂载到容器,但不属于联合文件系统,因此能够绕过Union File System 提供一些用于持续存储或共享数据的特性;卷的设计目的就是数据持久化,完全独立于容器的生命周期,因此docker不会在容器删除时,删除其挂载的数据卷。
特点:
- 数据卷可在容器之间共享或重用数据。
- 卷中的更改可以直接生效。
- 数据卷中的更改,不会包含在镜像中的更新。
- 数据卷的生命周期一直持续到没有容器使用它为止。
实施
docker run -it -v /宿主机绝对路径:/容器内目录:权限 镜像名
- 运行时挂载容器数据卷
[root@localhost home]# docker run -d -p 81:80 --name nginx-v -v /home/html:/usr/share/nginx/html nginx
ea0e3c42576a04a7066a0e0ff5e42e3571fff2b845161d49f2699ff88db60014
[root@localhost home]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
ea0e3c42576a nginx "/docker-entrypoint.…" 3 seconds ago Up 3 seconds 0.0.0.0:81->80/tcp, :::81->80/tcp nginx-v
- 查看nginx访问环境
- 我们看一下什么原因,先进入Nginx容器内,看到默认html路径下无任何文件。
[root@localhost home]# docker exec -it ea0e3c42576a /bin/bash
root@ea0e3c42576a:/# cd /usr/share/nginx/html
root@ea0e3c42576a:/usr/share/nginx/html# ls
root@ea0e3c42576a:/usr/share/nginx/html#
宿主机/home/html下也无任何文件。
[root@localhost html]# pwd
/home/html
[root@localhost html]# ls
- 此时我们从宿主机上传一个index.html
[root@localhost html]# touch index.html
[root@localhost html]# echo "hello nginx." >>index.html
[root@localhost html]# ls
index.html
- 我们再刷新页nginx访问页面
同时我们看下docker容器内
root@ea0e3c42576a:/usr/share/nginx/html# ls
index.html
root@ea0e3c42576a:/usr/share/nginx/html# cat index.html
hello nginx.
到这里我们能看到,宿主机添加文件后,docker容器内目录也会相应同步过来。
同理从宿主机删除文件后,docker容器内目录也会相应同步删除。
测试
我们从docker容器内添加文件,看宿主机是否同步
root@ea0e3c42576a:/usr/share/nginx/html# touch index.html
root@ea0e3c42576a:/usr/share/nginx/html# echo "from docker " >>index.html
root@ea0e3c42576a:/usr/share/nginx/html# ls
index.html
root@ea0e3c42576a:/usr/share/nginx/html# cat index.html
from docker
再看下宿主机
[root@localhost html]# ls
index.html
[root@localhost html]# cat index.html
from docker
我们发现从容器内添加文件后宿主机也会跟随同步;
结论
docker容器的挂载是双向同步。