When I bind-mount a folder that does not exist in the host, it gets created with root ownership:
$ echo $USER
boss
$ ls -lA
total 0
$ docker run -v ./config:/config hello-world
Hello from Docker!
[...]
$ ls -lA
total 0
drwxr-xr-x 1 root root 0 mar 15 18:58 config
Can I make docker create such folders with the current userâs ownership?
I think I can workaround this by creating the folder manually myself, but I would like to avoid that.
I am afraid there is not, not even if the container is started with a specific user id.
me@host bindtest $ ls -l
total 0
me@host bindtest $ sudo docker run --rm -u 1000:100 -v ./config:/config alpine id
uid=1000 gid=100(users) groups=100(users)
me@host bindtest ]$ ls -l
total 0
drwxr-xr-x 2 root root 6 MĂ€r 15 20:24 config
Many beginner-friendly images start the container as root, chmod/chown the folders in the entrypoint script so that the ownership and permissions are set as required. For other images, you need to manually take care of it.
Letting Docker create the source folder could be dangerous or at least problematic. You could accidentally use the wrong folder or run the command in the wrong context and create an empty folder somewhere you didnât want. So I always prefer using the long syntax in compose and the --mount option instead of -v with the docker run command so it doesnât create the folder automatically, but warns me if it doesnât exist.
Bind mounts will always be created as root as it has nothing to do with the content in the container. It is supposed to override it completely and there is nothing to tell Docker that you want to the daemon to create the folder as root when it is running as root. If you want Docker to automatically set the right permission, use volumes with a custom source path.
But it would mean more work for you than just precreating the folder and bind mounting it Also it would work only if the destination folder in the container is not empty.