Joaquin
Joaquin

Reputation: 2091

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

The problem:

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?).

My try:

I created the volume shared-volume:

docker volume create shared-volume

Then I want to run a new container that must write to that volume, if the volume is empty then the content of the some-directory-with-content/ will be written to the volume, thats great:

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

After that when I check shared-volume it contains the files that were in /some-directory-with-content/, here is where I dont know what is the correct way to write to this shared-volume from docker run or docker compose.

When I tried to did the same with the second container:

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

It only returns the previous content, and I know that is the expected, so here is where I didnt know if is not possible to achieve this write to shared-volume using docker run or docker-compose or what is the correct way.

Thanks in advance!

Upvotes: 0

Views: 495

Answers (1)

Neo Anderson
Neo Anderson

Reputation: 6340

You can pass sh commands when you run the container. In the example below, I am creating the file somefile in the mount if it does not exist. I am displaying the content of the file, then I am appending some-text in the file.

Simply run this command several times to test it.

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"

This is the expected result:

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

Upvotes: 1

Related Questions