Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I mount a Docker image as a volume in Docker?

I would like to distribute some larger static files/assets as a Docker image so that it is easy for user to pull those optional files down the same way they would be pulling the app itself. But I cannot really find a good way to expose files from one Docker image to the other? Is there a way to mount a Docker image itself (or a directory in it) as a volume to other Docker container?

I know that there are volume plugins I could use, but I could not find any where I could to this or something similar?

like image 238
Mitar Avatar asked May 19 '18 18:05

Mitar


2 Answers

Is possible create any directory of an image to a docker volume, but not full image. At least not in a pretty or simple way.

If you want to create a directory from your image as a docker volume you can create a named volume:

docker volume create your_volume
docker run -d \
  -it \
  --name=yourcontainer \
  -v your_volume:/dir_with_data_you_need \
  your_docker_image

From this point, you'll have accessible your_volume with data from image your_docker_image

Reason why you cannot mount the whole image in a volume is because docker doesn't let specify / as source of named volume. You'll get Cannot create container for service your-srv: invalid volume spec "/": invalid volume specification: '/' even if you try with docker-compose.

like image 111
Alejandro Galera Avatar answered Oct 17 '22 00:10

Alejandro Galera


Don't know any direct way.

You can use a folder in your host as a bridge to share things, this is a indirect way to acheive this.

docker run -d -v /any_of_your_host_folder:/your_assets_folder_in_your_image_container your_image
docker run -d -v /any_of_your_host_folder:/your_folder_of_your_new_container your_container_want_to_use_assets

For your_image, you need add CMD in dockerfile to copy the assets to your_assets_folder_in_your_image_container(the one you use as volume as CMD executes after volume)

This may waste time, but just at the first time the assets container starts. And after the container starts, the files in assets container in fact copy to the host folder, and has none business with assets image any more. So you can just delete the image of the assets image. Then no space waste.

You aim just want other people easy to use the assets, so why not afford script to them, automatically fetch the image -> start the container(CMD auto copy files to volume) -> delete the image/container -> the assets already on host, so people just use this host assets as a volume to do next things.

Of course, if container can directly use other image's resource, it is better than this solution. Anyway, this can be a solution although not perfect.

like image 39
atline Avatar answered Oct 16 '22 23:10

atline