Creating Images that Support User Owned Volume Mounts with Docker Desktop and Docker Engine

I help support an application that builds docker images to facilitate isolated builds in users’ environments.

To do this, we mount a project directory in to the container to run the build. Since we don’t want all the files owned by root, we use a user in the image that matches the ID of the user running the container.

This all seems to change with user namespaces in Docker Desktop since the root user is already mapped to the user running the container.

Is there a recommended way to accommodate this? Do the Dockerfiles need to conditionally use a non-root user based on the nature of Docker? Or maybe there’s another way to avoid root-owned files while supporting Docker and Docker Desktop?

You mention volume mounts in the topic title, but what you actually do is bind-mount. Using an actual volume would mean that Docker copies existing files to the volume which is in the virtual machine of Docker desktop or on your host machine in case of Docker Engine. Then the ownership will stay what it was.

If you bind-mount a folder to a container in case of rootless Docker, then indeed your local user becomes root in the container. Docker Desktop is similar, but also different since it is not actually rootless Docker, because in the virtual machine the usr is root, but the files from the host into the virtual machine will be mounted as root and doesn’t matter what the original user was. At leat this happens on macOS, but the behavior could be different on different platforms.

If you want to keep the userids, you can copy the files using docker copy instead of mounting. Depending on the size of the files, it could work, but not ideal.

You can add a build argument and let the user decide what is the best way on their platform. If they use rootles Docker, the situation is similar.

Another feature that can help is that when you mount a folder from the host into the container in Docker Desktop, you can exec into the container and use chown to change the ownership only in the container. So you could write a script that starts the container and changes the ownership inside. It won’t change on the host. I tried on macOS, but I remember the same on Windows. Since I don’t use Desktop on Linux, I don’t know about that.

1 Like