Reputation: 11834
CASE 1:
I am trying to mount a host folder dir1
to /dir1
inside docker
docker run --rm -it \
-v "$(pwd)/dir1":"/dir1" \
some_image /bin/bash
I see the permissions inside docker as
drwxr-xr-x 3 hostuser users 4096 Apr 18 13:51 dir1
CASE 2:
Where as if i try to mount a nested folder, i see the parent folders are created with root user and the only the last directory has the host user permission
docker run --rm -it \
-v "$(pwd)/dir1/dir2":"/dir1/dir2" \
some_image /bin/bash
here i see /dir1 permission inside docker as
drwxr-xr-x 3 root root 4096 Apr 18 13:51 dir1
and
here i see /dir1/dir2 permission inside docker as
drwxr-xr-x 3 hostuser users 4096 Apr 18 13:51 dir2
I am expecting both the dir1
and dir2
to have hostuser users
permissions
How can i achieve this
SOLUTION
docker run --rm -it \
-v "$(pwd)/dir1":"/dir1" \
-v "$(pwd)/dir1/dir2":"/dir1/dir2" \
someimage /bin/bash
I have to mount the parent folder also then i can see its permission as hostusers
Upvotes: 5
Views: 2322
Reputation: 264426
The dockerd
engine is running as root, it doesn't know anything about the user running the docker
process, just like a web server doesn't know the user id of the user running the browser.
What controls the UID is whether you have setup user namespaces (off by default because of the way they break these bind mounts), and the user of the process running inside the container. If your container is running as root, it will create files as the root user, exactly the same as if you ran any root process on Linux.
To override the default user configured in the image, you can pass the -u
flag:
docker run --rm -it \
-u "$(id -u):$(id -g)" \
-v "$(pwd)/dir1":"/dir1" \
some_image /bin/bash
However, realize that image creators expect their container to run with the uid they have configured, and there may be other changes to the image needed to support running the container as a different UID. I've often made images that handle this with a fixperms
script from my docker-base repo. I call that script as part of the entrypoint to modify the container UID to match the directory (volume mount) UID, and then run gosu
to switch from running as root to running as that container user.
Also note that dir1
should already exist on the host in advance. Otherwise, the docker engine has a feature where it will create the missing source folder for you, but doesn't know the permissions/ownership to give it, and just goes with the default root:root ownership. If docker didn't do that, the bind mount would fail, since Linux requires the bind mount source to already exist.
Exceptions to this are when the filesystem goes through some kind of intermediate layer, like NFS doing a squash, or Docker Desktop syncing the host directories with those of the embedded Linux VM.
Upvotes: 2