Single file volume mounted as directory in Docker

前端 未结 6 1791
春和景丽
春和景丽 2020-12-23 19:00

Docker documentation says that it\'s possible to mount a single file into a Docker container:

The -v flag can also be used to mount a single file - in

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-23 19:14

    A case where Docker might not find the file, even though you're sure it exists

    As edi9999 pointed out, if you tell the docker daemon to mount a file, it won't look into your current container's filesystem, it will look into the filesystem where the daemon is running.

    You might have this problem if your docker daemon is running elsewhere for some reason.

    ❯ docker run --rm -it -v /var/run/docker.sock:/var/run/docker.sock docker
    / # echo "bar" > /foo
    / # docker run --rm -v /foo:/foo ubuntu bash -c 'cat foo'
    cat: foo: Is a directory
    

    Docker can't find the /foo file on it's host, so it (helpfully?) creates a directory there so at least you've mounted something.

    A Workaround

    You can work around this by mounting a host directory into the outer container, and then using that directory for the volume you want to appear in the inner container:

    ❯ docker run --rm -it -v /var/run/docker.sock:/var/run/docker.sock -v /dev/shm:/dev/shm docker
    / # echo "bar" > /dev/shm/foo
    / # docker run --rm -v /dev/shm/foo:/dev/shm/foo ubuntu bash -c 'cat /dev/shm/foo'
    bar
    

    This makes the path /dev/shm/foo refer to the same file in either context, so you can reference the file from the outer container, and the daemon will find it on the the host, which means it will show up as itself in the inner container, rather than as a directory.

提交回复
热议问题