• 技术文章 >运维 >Docker

    docker容器重启后数据会丢吗

    长期闲置长期闲置2022-06-17 10:41:00原创337

    docker容器重启后数据会丢失的;但是可以利用volume或者“data container”来实现数据持久化,在容器关闭之后可以利用“-v”或者“–volumes-from”重新使用以前的数据,docker也可挂载宿主机磁盘目录,用来永久存储数据。

    本教程操作环境:linux7.3系统、docker19.03版、Dell G3电脑。

    docker容器重启后数据会丢吗

    会,大家在使用docker部署web应用或者mysql数据库时,会发现当容器重启后,容器运行过程中产生的日志或者数据库数据都会被清空。

    如果你想数据持久化,需使用volume或者data container,这样在容器关闭后可以再通过-v或者–volumes-from重新使用以前的数据。docker挂载宿主机磁盘目录,用来永久存储数据。

    创建容器时执行Docker Volume

    使用 docker run 命令,可以运行一个 Docker容器,使用镜像ubuntu/nginx,挂载本地目录/tmp/source到容器目录/tmp/destination

    docker run -itd --volume /tmp/source:/tmp/destination --name test ubuntu/nginx bash

    基于ubuntu/nginx镜像创建了一个Docker容器。指定容器的名称为test,由 ––name 选项指定。

    Docker Volume 由 ––volume (可以简写为-v)选项指定,主机的 /tmp/source 目录与容器中的 /tmp/destination 目录一一对应。

    查看Docker Volume

    使用 docker inspect 命令,可以查看 Docker容器 的详细信息:

    docker inspect --format='{{json .Mounts}}'test | python -m json.tool[{"Destination": "/tmp/destination",
    "Mode": "","Propagation": "","RW": true,"Source": "/tmp/source","Type": "bind"}]

    使用 ––format 选项,可以选择性查看需要的容器信息。 .Mount 为容器的 Docker Volume 信息。

    python -m json.tool 可以将输出的json字符串格式化显示。Source 表示主机上的目录,即 /tmp/source 。Destination 为容器中的目录,即 /tmp/destination。

    本机文件可以同步到容器

    在本机/tmp/source目录中新建hello.txt文件

    touch /tmp/source/hello.txtls /tmp/source/hello.txt

    hello.txt文件在容器/tmp/destination/目录中可见

    使用 docker exec 命令,可以在容器中执行命令。

    docker exectest ls /tmp/destination/hello.txt

    所以在宿主机对目录 /tmp/source/ 的修改,可以同步到容器目录 /tmp/destination/ 中。

    容器文件可以同步到宿主机

    在容器/tmp/destination目录中新建world.txt文件

    docker exec test touch /tmp/destination/world.txtdocker exec test ls /tmp/destination/hello.txtworld.txt

    world.txt文件在宿主机/tmp/source/目录中可见

    ls /tmp/source/hello.txt world.txt

    推荐学习:《docker视频教程

    以上就是docker容器重启后数据会丢吗的详细内容,更多请关注php中文网其它相关文章!

    声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
    专题推荐:Docker
    上一篇:docker是容器吗 下一篇:docker虚拟化是什么
    20期PHP线上班

    相关文章推荐

    • 【活动】充值PHP中文网VIP即送云服务器• docker容器的状态有哪几种• docker是一种什么技术• docker官方镜像有哪些• 在docker中内容无关性是指什么• 什么是docker最早支持的存储引擎
    1/1

    PHP中文网