Single File Volume Mounted as Directory in Docker

How to mount a single file in a volume


TL;DR/Notice:


If you experience a directory being created in place of the file you are trying to mount, you have probably failed to supply a valid and absolute path. This is a common mistake with a silent and confusing failure mode.

File volumes are done this way in docker (absolute path example (can use env variables), and you need to mention the file name) :

    volumes:
- /src/docker/myapp/upload:/var/www/html/upload
- /src/docker/myapp/upload/config.php:/var/www/html/config.php

You can also do:

    volumes:
- ${PWD}/upload:/var/www/html/upload
- ${PWD}/upload/config.php:/var/www/html/config.php

If you fire the docker-compose from /src/docker/myapp folder

Single file volume mounted as directory in Docker

test is the name of your image that you have built with 'docker build -t test', not a /test folder.

Try a Dockerfile with:

CMD ["ls", "-lah", "/"]
or
CMD ["cat", "/file.json"]

And:

docker run --rm -it -v $(pwd)/file.json:/file.json test

Note the use of $(pwd) in order to mount a file with its full absolute path (relative paths are not supported)

By using $(pwd), you will get an absolute path which does exists, and respect the case, as opposed to a file name or path which might not exist.

An non-existing host path would be mounted as a folder in the container.

docker-compose mount single file with directory

Your example works fine for me.

# docker-compose --version
docker-compose version 1.25.0, build unknown

Since you mentioned that even with explicit path it was not working, while it was working inside your main folder, I would suggest to check the permissions for the myconfig folder. Make sure all users are allowed access and read ('x' and 'r')

# ls -ltr
total 8
drwxr-xr-x 2 root root 4096 Feb 23 06:03 myconfig
-rw-r--r-- 1 root root 182 Feb 23 06:05 docker-compose.yml

if the the permissions are not correct, set them with chmod a+xr myconfig/ and chmod a+r myconfig/nginx.conf

Single file mount to docker container is not working

I've figured out what the issue is. when mounting a single file and editing it, use the nano editor to edit the files or turn off swapfiles before using vim. when using vim, its creating a swapfile and replacing the existing one. therefore the file bind link is breaking. thats why the changes are not reflecting both sides.



Related Topics



Leave a reply



Submit