Docker volume and host permissions

2019-07-24 23:39发布

When I run a docker image for example like

docker run -v /home/n1/workspace:/root/workspace -it rust:latest bash

and I create a directory in the container like

mkdir /root/workspace/test

It's owned by root on my host machine. Which leads to I have to change the permissions everytime after I turn of the container to be able to operate with that directory.

Is there a way how to tell Docker to handle directories and files from my machine (host machine) point of view under a certain user?

2条回答
Viruses.
2楼-- · 2019-07-24 23:59

Sure, because Docker uses root as a default user. You should create user in your docker container, switch to that user and then make folder, then you will get them without root permissions on you host machine.

Dockerfile

FROM rust:latest
...
RUN useradd -ms /bin/bash myuser
USER myuser
查看更多
等我变得足够好
3楼-- · 2019-07-25 00:19

You need to run your application as the same uid inside the container as you do on the host to get file ownership to match. My own solution for this is to start the container as root, adjust the uid of the user inside the container to match the volume mount, and then su to the user to run the app. Scripts for this can be found in this repo: https://github.com/sudo-bmitch/docker-base

The in that repo, the fix-perms script handles the change in uid/gid inside the container, and the entrypoint script has an exec gosu $username "$@" that runs the app as the selected user.

查看更多
登录 后发表回答