首页 > 解决方案 > File created in interactive session within container dissapears after exiting container (container running in background)

问题描述


Objective

Essentially what I am trying to accomplish is to install a bunch of software but store the commands run in the Dockerfile in the end. I was planning on recording the installation process by running the "script" function to record the commands run on the command line. I would like to know why it doesn't work but if there is a better way of doing it, I am all ears!


The issue

I'm sure there is a simple answer to this but I can't seem to figure it out. When I create a dummy file within my docker container it dissapears when I exit the container even though the container is running in the background.


Attempt

This is my Dockerfile

##Filename = Dockerfile
FROM centos:7

WORKDIR /dummy_folder

CMD ["echo", "hello world"]

I build the image and run it in the background.

docker build -t my_test_image:v1.0 .
docker run -d e9e949b5d85a tail -f /dev/null

现在我可以看到我的容器在后台运行

docker ps
CONTAINER ID        IMAGE               COMMAND               CREATED             STATUS              PORTS               NAMES
6f4da7a1b74d        e9e949b5d85a        "tail -f /dev/null"   14 minutes ago      Up 14 minutes                           trusting_poincare

如果我创建一个交互式会话并在 /dummy_folder 中转储一个文件并退出。当我创建一个新的交互式会话时 /dummy_folder 再次为空。

docker run -it e9e949b5d85a /bin/bash
echo "dummy" > dummy
exit
docker run -it e9e949b5d85a /bin/bash
ls -alh /dummy_folder

PS tail -f /dev/null 只是我用来保持容器在后台运行的一个技巧,因为仅使用标志 -d 运行它显然不适用于 centos 容器。

我正在运行 Docker 版本 19.03.8,构建 afacb8b

谢谢萨布里

标签: dockercontainers

解决方案


每次运行时,您都在创建一个新容器docker run ...。我认为你想要做的是在你开始使用的同一个容器上运行一个 shell docker run -d e9e949b5d85a tail -f /dev/null。如果是这样,您正在寻找的 Docker 命令是exec

使用容器 ID(而不是图像 ID)启动交互式会话并执行您的操作

docker exec -it 6f4da7a1b74d /bin/bash
$ echo "dummy" > dummy
$ exit

然后再次检查内容exec

docker exec 6f4da7a1b74d ls -alh /dummy_folder

推荐阅读