Reattaching orphaned docker volumes

2019-05-18 19:08发布

问题:

I'm using a docker volume, specified in my dockerfile so that my data can persist on the host. The dockerfile looks something like this:

FROM base-image
VOLUME /path/to/something
RUN do_stuff
....

When I run the container it creates a volume (call it VolumeA) which I can see when I do a docker volume ls.

If I stop and remove the container, the VolumeA sticks around as expected.

My question is, if I run a new version of the container, is there a way to use VolumeA rather than have it create a new one?

回答1:

I prefer using named volumes, as you can mount them easily to a new container.

But for unnamed volume, I:

  • run my container (the VOLUME directive causes it to create a new volume to a new path that you can get by inspecting it)
  • move the path of the old volume to that new path.

Before docker volume commands, I used to do that with a script: updateDataContainerPath.sh.

But again, these days, none of my images have a VOLUME in them: I create separately named volumes (docker volume create), and mount them to containers at runtime (docker run -v my-named-volume:/my/path)



回答2:

You might use the -v flag in the docker run command to bind the existing volume to your new docker container

docker run -v VolumeA:/path/to/something [image]

Also look into the --volumes-from flag to mount volumes used or created by other containers.

https://docs.docker.com/engine/reference/commandline/run/ https://docs.docker.com/engine/reference/commandline/volume_create/