如何从 docker-compose 或 docker 运行 写入现有的填充卷

How to write to an existing populated volume from docker-compose or docker run

问题:

I want to have a volume that is shared between a few containers. The idea is to add/write information to this shared volume when a container is initialized using docker run or docker compose(there is another way?).

我的尝试:

我创建了卷 shared-volume:

docker volume create shared-volume

然后我想运行一个必须写入那个卷的新容器,如果卷是空的那么some-directory-with-content/的内容将写入卷,太棒了:

docker run -ti --rm --mount source=shared-volume,target=/some-directory-with-content/ custom-image

在那之后,当我检查 shared-volume 它包含 /some-directory-with-content/ 中的文件时,我不知道从 shared-volume 写入这个 shared-volume 的正确方法是什么=41=] 运行 或 docker 撰写.

当我尝试对第二个容器执行相同操作时:

docker run -ti --rm --mount source=shared-volume,target=/another-directory-with-content/ custom-image

它只有 returns 以前的内容,我知道这是预期的,所以这里是我不知道是否无法使用 [=41= 写入 shared-volume 的地方] 运行 或 docker-compose 或正确的方法是什么。

提前致谢!

当您 运行 容器时,您可以传递 sh 命令。在下面的示例中,如果文件 somefile 不存在,我将在挂载中创建它。我正在显示文件的内容,然后我在文件中附加 some-text

只需运行多次执行此命令即可测试

docker run \
  --rm \
  --mount source=shared-volume,target=/some-directory-with-content/ \
  alpine \
  sh -c "touch /some-directory-with-content/somefile && cat /some-directory-with-content/somefile && echo "some-text" >> /some-directory-with-content/somefile"

这是预期的结果:

neo@neo-desktop:shared-vol-demo$ docker run --rm --mount source=shared-volume,target=/some-directory-with-content/ alpine sh -c "touch /some-directory-with-content/somefile && cat /some-directory-with-content/somefile && echo "some-text" >> /some-directory-with-content/somefile"
neo@neo-desktop:shared-vol-demo$ docker run --rm --mount source=shared-volume,target=/some-directory-with-content/ alpine sh -c "touch /some-directory-with-content/somefile && cat /some-directory-with-content/somefile && echo "some-text" >> /some-directory-with-content/somefile"
some-text
neo@neo-desktop:shared-vol-demo$ docker run --rm --mount source=shared-volume,target=/some-directory-with-content/ alpine sh -c "touch /some-directory-with-content/somefile && cat /some-directory-with-content/somefile && echo "some-text" >> /some-directory-with-content/somefile"
some-text
some-text