浅谈docker容器数据持久化

  可以理解成一个容器是为了短暂存在而设计的,容器可能随时被创建或销毁,docker提供了两种方式将数据从宿主机挂载的容器中:

  • volumes:docker自己管理宿主机文件系统的一部分,默认存储路径为 /var/lib/docker/volumes;
  • bind mounts:将宿主机的任意位置的文件或者目录挂载到容器 (一般习惯用法)

Docker 默认的镜像和容器存储位置在/var/lib/docker中,如果系统部署架构为 OS Disk + Data Disk 方式,在大量使用时,建议变更默认存储的位置,避免大量数据存储在 OS Disk,使用中途变更,经测试,在拷贝后原存储在/var/lib/docker/*的容器和镜像数据不被新路径读取。

[root@SH2-SVVL-Q911 ~]# cd /etc/systemd/system/multi-user.target.wants
[root@SH2-SVVL-Q911 multi-user.target.wants]# vim docker.service 
ExecStart=/usr/bin/dockerd --graph=/data/docker --storage-driver=overlay --registry-mirror=https://jxus37ad.mirror.aliyuncs.com # --graph=/data/docker :docker新的存储位置 ;--storage-driver=overlay :当前docker所使用的存储驱动
[root@SH2-SVVL-Q911 multi-user.target.wants]# systemctl daemon-reload
[root@SH2-SVVL-Q911 multi-user.target.wants]# systemctl restart docker

示例分析:

[root@SH2-SVVL-Q911 ~]# docker run -d --name web -p 8003:80 nginx # 展示的是nginx默认页面
[root@SH2-SVVL-Q911 ~]# firewall-cmd --permanent --zone=public --add-port=8003/tcp
[root@SH2-SVVL-Q911 ~]# firewall-cmd --complete-reload
[root@SH2-SVVL-Q911 ~]# docker exec -it web bash
root@0c13f9e2202b:/# cd /usr/share/nginx/html/
root@0c13f9e2202b:/usr/share/nginx/html# ls
50x.html  index.html
root@0c13f9e2202b:/usr/share/nginx/html# echo "<h1>hello ponfey</h1>" > index.html  # 展示自定义内容页面

[root@SH2-SVVL-Q911 ~]# docker rm -f web # 销毁容器后重新创建,展示的是nginx默认页面,不会是自定义页面内容
[root@SH2-SVVL-Q911 ~]# mkdir /opt/wwwroot
[root@SH2-SVVL-Q911 ~]# docker run -d --name web -p 8003:80 -v /opt/wwwroot/:/usr/share/nginx/html nginx # 展示403页面,这是bind mounts的一个特性,/opt/wwwroot这是一个空目录,宿主机文件会隐藏掉容器内的数据文件
[root@SH2-SVVL-Q911 ~]# docker exec -it web bash
root@a4dd8daaba57:/# cd /usr/share/nginx/html/
root@a4dd8daaba57:/usr/share/nginx/html# echo "<h1>hello ponfey</h1>" > index.html #  展示自定义内容页面,页面可以重新访问

容器的目录一定是要持久化的目录,一般启动一个容器,只有个别的数据目录是需要持久化的
,更要注意的是,随着容器启动而产生的数据才会被持久化,而不是已有的数据被持久化,已有的数据只能算是镜像中的一部分,已经是个模板。

  Docker部署的jenkins、gitlab等都是采用 -v 将他们自身产生的数据持久化宿主机。

上一篇
下一篇