千家信息网

Docker入门与应用实战之管理应用程序数据

发表于:2025-02-02 作者:千家信息网编辑
千家信息网最后更新 2025年02月02日,1.将数据从宿主机挂载到容器中的三种方式Docker提供三种方式将数据从宿主机挂载到容器中: • volumes:Docker管理宿主机文件系统的一部分(/var/lib/docker/volumes
千家信息网最后更新 2025年02月02日Docker入门与应用实战之管理应用程序数据


1.将数据从宿主机挂载到容器中的三种方式

Docker提供三种方式将数据从宿主机挂载到容器中: • volumes:Docker管理宿主机文件系统的一部分(/var/lib/docker/volumes)。保存数据的最佳方式。 • bind mounts:将宿主机上的任意位置的文件或者目录挂载到容器中。 • tmpfs:挂载存储在主机系统的内存中,而不会写入主机的文件系统。如果不希望将数据持久存储在任何位置,可以使用 tmpfs,同时避免写入容器可写层提高性能。

2.Volume

创建卷:docker volume create nginx-vol查看卷:docker volume lsdocker volume inspect nginx-vol挂载卷:docker run -d -p 89:80 --name=nginx-test --mount src=nginx-vol,dst=/usr/share/nginx/html nginx docker run -d -p 89:80 --name=nginx-test -v nginx-vol:/usr/share/nginx/html nginx 删除卷:docker rm -f $(docker ps -a |awk '{print $1}')docker rm -f $(docker ps -qa)docker volume rm nginx-vol注意: 1. 如果没有指定卷,自动创建。 2. 建议使用--mount,更通用

3.Bind Mounts

用卷创建一个容器:docker run -d -it --name=nginx-test --mount type=bind,src=/app/wwwroot,dst=/usr/share/nginx/html nginxdocker run -d -it --name=nginx-test -v /app/wwwroot:/usr/share/nginx/html nginx 验证绑定:docker inspect nginx-test 清理:docker stop nginx-testdocker rm nginx-test 注意: 1. 如果源文件/目录没有存在,不会自动创建,会抛出一个错误。 2. 如果挂载目标在容器中非空目录,则该目录现有内容将被隐藏[root@localhost ~]# mkdir wwwroot;touch wwwroot/index.html[root@localhost ~]# docker run -d -p 89:80 --mount type=bind,src=$PWD/wwwroot,dst=/usr/share/nginx/html nginx9c675487b319d6a723f2de35abd09c465aca6472b91e7232a9de6893012f3f63[root@localhost ~]# docker psCONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                NAMES9c675487b319        nginx               "nginx -g 'daemon of…"   9 seconds ago       Up 8 seconds        0.0.0.0:89->80/tcp   sad_robinson[root@localhost ~]# docker exec -it 9c675487b319 bashroot@9c675487b319:/# ls /usr/share/nginx/htmlindex.htmlroot@9c675487b319:/# cat /usr/share/nginx/html/index.html root@9c675487b319:/# exitexit[root@localhost ~]# cat wwwroot/index.html [root@localhost ~]# echo "hello" >wwwroot/index.html [root@localhost ~]# docker exec -it 9c675487b319 cat /usr/share/nginx/html/index.htmlhello[root@localhost ~]# docker rm -f 9c675487b9c675487b[root@localhost ~]# cat wwwroot/index.html hello[root@localhost ~]#


0