Understanding user file ownership in docker: how to avoid changing permissions of linked volumes

Two options I’ve found:

CHOWN all the things (after doing your work)

I’ve done docker run -v `pwd`/shared:/shared image, and the container has created files within pwd/shared that are how owned by the docker process. However, /shared is still owned by me. So within the docker process, I do

chown -R `stat -c "%u:%g" /shared` /shared

stat -c "%u:%g" /shared returns 1000:1000 in my case, being the uid:gid of my user. Even though there is no user 1000 within the docker conatainer, the id is there (and stat /shared just says “unknown” if you ask for the username).

Anyway, chown obediently transfers ownership of the contents of /shared to 1000:1000 (which, as far as it is concerned, doesn’t exist, but outside the container, it’s me). So I now own all the files. The container can still modify things if it wants to, because from its perspective, it’s root.

And all is well with the world.

docker run -u so all files created will automatically have the right owner

Another way to do this is the -u flag on docker run.

docker run -v `pwd`/shared:/shared -u `stat -c "%u:%g" /shared` ubuntu bash

This way, the docker user inside the container is youruid:yourgid.

However: this means giving up your root authority within the container (apt-get install, etc.). Unless you create a user with that new uid and add it to the root group.

Leave a Comment