4

Please bear with me as I learn my way around docker. I'm using v1.11.1

I am making a Dockerfile and would like to specify that a folder of the container should be persisted, this should only be persisted per user (computer running the container). I originally thought that including:

VOLUME /path/to/dir/to/persist

would be enough, but when I start my container with docker run -t -i myimage:latest bash and manually add files in then exit I expect to be able to find my files again. But when I run the image again (as per above) the added files are no longer there.

I've read around but answers seem either outdated in regards to the use of VOLUMES, or suggest things I would rather not do, which is:

  • I don't want to use -v in the run command
  • I would rather not make a volume container (seems like overkill for my one tiny folder)

What is it that I'm doing wrong? Any help would be greatly appreciated.

Cheers guys.

Update: I can persist data using a named volume ie: docker run -v name:/path/to/persist -t -i myimage:latest bash But building with a Dockerfile that contains VOLUME name:/path/to/persist does not work.

4

1 回答 1

9

不太明显的是,每次执行“docker run”时,您都在创建一个全新的容器。然后每个新容器都会有一个新的卷。

所以你的数据被持久化了,但你没有从你写入的容器中读取数据。

举例说明问题

示例 Dockerfile

FROM ubuntu
VOLUME /data

正常建造

$ docker build . -t myimage
Sending build context to Docker daemon 2.048 kB
Step 1 : FROM ubuntu
 ---> bd3d4369aebc
Step 2 : VOLUME /data
 ---> Running in db84d80841de
 ---> 7c94335543b8

现在运行两次

$ docker run -ti myimage echo hello world
$ docker run -ti myimage echo hello world

看看卷

$ docker volume ls
DRIVER              VOLUME NAME
local               078820609d31f814cd5704cf419c3f579af30672411c476c4972a4aad3a3916c
local               cad0604d02467a02f2148a77992b1429bb655dba8137351d392b77a25f30192b

“docker rm”命令有一个特殊的“-v”选项,可以清理与容器相关的所有卷。

$ docker rm -v $(docker ps -qa)

如何使用数据容器

使用上一个示例中构建的相同 docker 映像创建一个容器,其唯一目的是通过其卷保存数据

$ docker create --name mydata myimage

启动另一个容器,将一些数据保存到“/data”卷中

$ docker run -it --rm --volumes-from mydata myimage bash
root@a1227abdc212:/# echo hello world > /data/helloworld.txt
root@a1227abdc212:/# exit

启动第二个容器来检索数据

$ docker run -it --rm --volumes-from mydata myimage cat /data/helloworld.txt
hello world

清理,只需删除容器并指定“-v”选项以确保清理其卷。

$ docker rm -v mydata

笔记:

  • “volumes-from”参数意味着所有数据都保存到与“mydata”容器关联的底层卷中
  • 运行容器时,“rm”选项将确保它们被自动删除,这对于一次性容器很有用。
于 2016-09-04T16:51:07.700 回答