Docker – How to create image from docker containing that includes volume data

docker

Consider a Dockerfile that declares two volumes

FROM someimage
# ...
VOLUME ["/foo", "/bar"]

and a container started from that image, that does a bind mount for one of those volumes:

docker run --name mycontainer -d -v /some/path:/foo myimage

If I created a new image from that container using

docker commit mycontainer myexportedimage

both paths, /foo and /bar, will be excluded in the exported image.

How do I create a runnable (i.e. maintaining meta data from Dockerfile) image from mycontainer that includes the data from both paths, /foo (bind mounted) and /bar (volume as declared by Dockerfile), so if I exported the image to another Docker host, all data would be present?

Best Answer

Disclaimer : answer is incomplete because you won't be able to manage that from a Dockerfile like asked and the point is taken that "we should not be in this situation and we should not try to solve this problem in that manner".

I know this is an old question but I ran into the same situation and here's what I did.

You can create an image with the content of your volumes using docker cp to import the content of your volume locally into the container (just copy it somewhere else in your running container and be aware that this duplicates data so watch you filesystem usage). Or exec into it and use cp commands to copy the data in your mounted volume somewhere else (ie: in a tmp directory).

Then, you can docker commit that container to turn it into an image. Run a new container from that new image without using docker volumes and move back the files copied where they should be if the volumes where mounted.

Now, use docker commit again to get a reusable image from the container where you copied your volumes contents.

You can now tag and/or push that image to a registry or docker save it into an archive and use it where you need it.