Understanding user file ownership in docker: how to avoid changing permissions of linked volumes

后端 未结 3 1230
甜味超标
甜味超标 2020-11-28 20:26

Consider the following trivial Dockerfile:

FROM debian:testing
RUN  adduser --disabled-password --gecos \'\' docker
RUN  adduser --disabled-password --gecos          


        
3条回答
  •  清歌不尽
    2020-11-28 21:10

    So, I ended up in this post looking on how to restore ownership of all the files (owned by root) that came out of a docker container running as root, to my non-privileged user in the host.

    I needed the process inside the container to run as root, so I can't use -u on docker run.

    I'm not proud of what I did, but at the end of my bash script, I added this:

    docker run --rm -it \
        --entrypoint /bin/sh \
        -e HOST_UID=`id -u` \
        -v ${HOST_FOLDER_OWNED_BY_ROOT}:/tmp \
        alpine:latest \
        -c 'chown -R ${HOST_UID}:${HOST_UID} /tmp/'
    

    Let's break some of the lines down:

    • Run /bin/sh inside the container:

    --entrypoint /bin/sh

    • Pass the current user's uid as an environment variable to the container:

    -e HOST_UID=`id -u`

    • Mount whatever folder you want to re-own back to your user (filled with files owned by root, output-ed by the previous container that ran as root), under this new container's /tmp:

    -v ${HOST_FOLDER_OWNED_BY_ROOT}:/tmp

    • Run chown recursively with the host user's uid over the target directory (mounted inside the container in /tmp):

    -c 'chown -R ${HOST_UID}:${HOST_UID} /tmp/'

    So, with this, I got the files owned back to my current user without having to "escalate" privileges to root or to sudo.

    It's dirty, but it worked. Hope I helped.

提交回复
热议问题