Docker creates files as root in mounted volume [duplicate]

对着背影说爱祢 提交于 2019-11-27 14:25:44

问题


This question already has an answer here:

  • Share files between host system and docker container using specific UID 4 answers

I'm using Docker (1.3.1) to build RPMs inside a container:

docker run -v /home/matt/build:/build build-rpm /build/build-pkg.sh

This works fine (my user is in the docker group, so I don't need to sudo) and drops a completed .rpm file in the current directory. The problem is that the file is created as owned by root.

How can I arrange it so that the file is created owned by the same user as I run docker with?


回答1:


You could try to create (in the Dockerfile of a custom image) a user and set it as the one used by the container

RUN adduser --system --group --shell /bin/sh auser \
 && mkdir /home/auser/bin
USER auser

Then check if a docker run -v /home/matt/build:/build build-rpm mounts the shared folder in /build as auser.


Another option mentioned in issue 2259:

If you chown the volume (on the host side) before bind-mounting it, it will work.
In that case, you could do:

mkdir /tmp/www
chown 101:101 /tmp/www
docker run -v /tmp/www:/var/www ubuntu stat -c "%U %G" /var/www

(Assuming that 101:101 is the UID:GID of the www-data user in your container.)




回答2:


Docker runs as root and has no idea what your user is inside its virtual environment (even if you're in the sudoers group). But you can create a non-root user while building your docker image that can be called whatever you like.

# create a non-root user named tester, 
# give them the password "tester" put them in the sudo group
RUN useradd -d /home/tester -m -s /bin/bash tester && echo "tester:tester" | chpasswd && adduser tester sudo

# start working in the "tester" home directory
WORKDIR /home/tester
COPY ./src

# Make the files owned by tester
RUN chown -R tester:tester /home/tester

# Switch to your new user in the docker image
USER tester


来源:https://stackoverflow.com/questions/30052019/docker-creates-files-as-root-in-mounted-volume

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!