2017-03-16 - starting container as non-root

docker logo around the end of last year i spent some time investigating how to run a script, that runs some command in docker container, with a user/group of a local user, that has started the script. this was important to me, so that files that docker container create on a mounted volume are not owned by root:root, but me:me instead (i.e. user that started the container). the problem is, that different users have different UIDs/GIDs, on different machines. how to unify this?

there is a -u switch do docker run, that allows to pass in user and a group. it looked very promising at first:

docker run -it --rm -u oops debian:testing

…but it failed:

docker: Error response from daemon: linux spec user: unable to find user oops: no matching entries in passwd file.

user must exist in the image, in order to start this way. i've played around a lot with different options, helper proxy scripts, parameters/UIDs deduction, etc… finally it turned out there is a super simple, but not widely known solution: -u switch also accepts UIDs and GIDs, and then they do not need to map to any user inside the container!

docker run -it --rm -u 666:999 debian:testing
I have no name!@07bf48e8b622:/$ id
uid=666 gid=999 groups=999

from here on it was simple. for the sake of example let's assume we want to mount users ~/data directory, to /mount directory in the container, while making sure that files generated by a container map to user who runs the command. the spell is:

docker run -it --rm -u "$(id -u):$(id -g)" -v ~/data:/mnt my_image some_cmd

hope this will save you some time. enjoy! :)

blog/2017/03/16/2017-03-16_-_starting_container_as_non-root.txt · Last modified: 2017/03/16 18:29 by basz
Back to top
Valid CSS Driven by DokuWiki Recent changes RSS feed Valid XHTML 1.0