本教程操作环境:linux5.9.8系统、docker-1.13.1版、dell g3电脑。
停止docker容器,数据不会丢失。
docker容器停止并退出,会处于终止(exited)状态,等同于虚拟机关机,所以是不会有数据丢失的。
此时可以通过 docker ps -a 查看,还可以通过docker start 来启动,只有删除容器才会清除数据。
只有当docker rm之后,删除容器才会清除数据。
创建容器,然后把容器删除,数据随着容器的删除也被删除
如何删除容器不删除数据,在创建容器的时候dockerrun-vhost_dir:containere_dir这样可以解决你的问题!
扩展知识:当容器重启后,容器运行过程中产生的日志或者数据库数据都会被清空。
解决方法:
docker可以通过挂载宿主机磁盘目录,来永久存储数据。
1. 创建容器时执行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 目录一一对应。
2. 查看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。
3. 本机文件可以同步到容器
在本机/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/ 中。
4. 容器文件可以同步到宿主机
在容器/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容器数据是否会丢失的详细内容。
