2

Background

I wish to make sure all people and automated processes working with my project use the exact same version and environment of some tool which has to do work on the host file system.

Instead of running /usr/bin/xyz or whatever, people will then use a wrapper/shim script similar to:

docker run -ti --rm \
  -v $PWD:/workdir \
  -v $HOME/.ssh:/root/.ssh \
  dockerizedxyz "$@"

This is working splendidly but...

Problem

Obviously, if I stop right here, then files created by the xyz running inside the container will be ending up belonging to root:root on the host. It is clear why this happens, and as expected.

Hence, I have enabled user namespaces for the docker demon. This works fine as well. My host user has UID 1000 and the subuid 493216.

If I run the docker-xyz-shim in a directory (on the host) that belongs to 1000, and if that container starts to create files, my expectation at first had been that they would have ended up as belonging to 1000 on the host (i.e., forward- and backward-mapping).

But, lo and behold, they belong to 493216, i.e., they belong to the subuid instead of the host uid. There is only a forward-mapping happening (from host-uid to sub-uid, no backward-mapping from sub-uid to host-uid).

I understand why that is, and that this is working as intended. First, there is a 1:n mapping involved, and it would be non-trivial to map the potentialla 65536 sub-uid back to the one host-uid. It allows us to do all kinds of things that would be practical in other use-cases. But in my particular case, I actually do wish the files to end up with 1000 on the host.

Is there anything I can do about it?

What I tried

I added the host user 493216 to the host group 1000 and set the g+rwx permissions. If I do a su - 493216 on the host, I can now edit the files belonging to 1000. But from inside the container, the files are shown to be owned by nobody:nobody and I can read them, but not write them.

I can create new files inside the container if I do a chmod 777 on a directory on the host (it then belongs to nobody:nobdy with 777 permissions in the container), and they end up belonging to root:root in the container (fine) and to 493216:493216 on the host (to be expected after all this).

EDIT: replaced "git" with "xyz", this is not about git at all, but about how to modify host files from inside a docker container without having root on the host.

Dan Cornilescu
  • 6,780
  • 2
  • 21
  • 45
AnoE
  • 4,936
  • 14
  • 26

1 Answers1

2
docker run -ti --rm \
  -v $PWD:/workdir \
  -v $HOME/.ssh:/root/.ssh \
  --user $(id -u):$(id -g) \
  dockerizedxyz "$@"

As long as you're not doing anything funny with the entrypoint in the container, this will leave files owned as the user that invoked Docker.

user2640621
  • 1,405
  • 9
  • 20