6、Docker 容器数据卷(挂载)

  docker 容器数据卷是容器在运行过程中持久化数据的一种方式,卷是目录或文件,存在于一个或多个容器中,由docker 挂载到容器,但不属于联合文件系统,因此能够绕过Union File System  提供一些用于持续存储或共享数据的特性;卷的设计目的就是数据持久化,完全独立于容器的生命周期,因此docker不会在容器删除时,删除其挂载的数据卷。

特点:

  1. 数据卷可在容器之间共享或重用数据。
  2. 卷中的更改可以直接生效。
  3. 数据卷中的更改,不会包含在镜像中的更新。
  4. 数据卷的生命周期一直持续到没有容器使用它为止。

实施

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容器的挂载是双向同步。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值