Can I have different users of file that is shared between host and docker container

Viewed 17

I have folder /opt/someName.json on the host.

I want to share this file with docker container but I do not want to copy it. I want to be able to change this file on the host and that it can be automatically used by docker container.

I want that on the host machine /opt/someName.json has mod: 770, owner:"a", user: "a" and in docker container I want that this file has mode 777, owner: "b", user: "b". User "a" and user "b" do not have same uid nor on host machine nor on docker-container.

Is this possible to be done?

1 Answers

A bind-mounted file will have the same numeric user and group owner IDs and the same permissions in all contexts. You can't set it to have one owner in one container and a totally different permission set in a different container.

Let's say the file is mode 0664 (read/write by user/group owner, read-only by others) and owned by user ID 1234 and group ID 5678.

$ ls -ln the-file
-rw-rw-r---   1 1234  5678  12 Sep 16  2022  the-file

So long as the main container process has the numeric group ID 5678, it can write the file. There's no particular requirement that this be the only group ID it has, or that the group ID exist in /etc/group in the container filesystem. docker run --group-add can give the container process additional group IDs.

docker run --rm \
  -v "$PWD:/data" \
  --group-add 5678 \
  busybox \
  sh -c 'echo "something else" > /data/the-file'

The more common case is just to set the container to run with the user and group IDs of the host user

docker run -u $(id -u):$(id -g) ...

It should be possible to construct your container to write in at most a single directory (so the bind-mount to /data above for example). In this case as long as the code is world-readable it doesn't matter which user owns it, and the only place this uid matters is writing to the data directory. (Writing to zero data directories is even better and avoids this problem entirely.)

Related