Larry Cai
Larry Cai

Reputation: 59953

can I mount a file from volume in docker to the container?

I put one security file like id_rsa in the docker volume larrycai_vol, trying to mount this into the container as a file.

$ docker volume inspect larrycai-vol
[
    {
        "CreatedAt": "2018-05-18T06:02:24Z",
        "Driver": "local",
        "Labels": {},
        "Mountpoint": "/var/lib/docker/volumes/larrycai-vol/_data",
        "Name": "larrycai-vol",
        "Options": {},
        "Scope": "local"
    }
]

Do we have some command like below (it doesn't work now)

docker run -it -v larrycai-vol/id_rsa:/root/.ssh/id_rsa own_ubuntu

I know it works if I mount file from docker host

docker run -it -v $PWD/.ssh/id_rsa:/root/.ssh/id_rsa own_ubuntu

Upvotes: 2

Views: 7450

Answers (1)

Alejandro Galera
Alejandro Galera

Reputation: 3691

Please, let me a couple of considerations furthermore the proposed solution to avoid further misunderstandings.

  • Docker allows mounting volumes (deployed from path dir of your host to docker path, i.e, -v $PWD/.ssh:/root/.ssh = it'd replace complete .ssh folder in destination, so, it's not recommended although possible)
  • Docker allows mounting named volumes (deployed from named volume name to docker path, i.e, -v larrycai-vol:/root/.ssh = it'd replace complete .ssh folder in destination, so, it's not recommended although possible)
  • Docker allows mounting files from host to a docker (example: -v $PWD/.ssh/id_rsa:/root/.ssh/id_rsa = your second example)
  • Docker allows mounting files from named volume to a docker (example: -v /var/lib/docker/volumes/YOUR_NAMED_VOLUME_NAME/_data/file:/dest_dir/file = what you're trying to do)

Your mistake is that you're telling docker to mount id_rsa from your larrycai-vol directory, not from docker named volume. In other words, three following commands are equivalent:

docker run -it -v ./larrycai-vol/id_rsa:/root/.ssh/id_rsa own_ubuntu
docker run -it -v $PWD/larrycai-vol/id_rsa:/root/.ssh/id_rsa own_ubuntu
docker run -it -v larrycai-vol/id_rsa:/root/.ssh/id_rsa own_ubuntu

So, if larrycai-vol directory (not named volume, but directory in your host) doesn't exist, command doesn't work as you want.

Definitively, to do what you're trying you have to create a bind volumeto the directory where named volume store data.

docker run -it -v /var/lib/docker/volumes/larrycai-vol/_data/id_rsa:/root/.ssh/id_rsa own_ubuntu

Upvotes: 6

Related Questions