Docker creates files as root in mounted volume [duplicate]

This question already has an answer here:

  • Using host environment variables with Dockerfile

    3 answers

  • VOLUME command in docker image is using custom-volume driver
  • Docker - ERROR: failed to register layer: symlink
  • How to access docker container via its Ip from the host
  • systemd service is not running on reboot
  • docker invalid characters for local volume name
  • Pulling image from local docker insecured Docker registry to Kubernetes
  • Docker error cannot delete docker container, conflict: unable to remove repository reference
  • What information is kept by a non-running docker container?
  • How to display output in a simple dockerized Python application?
  • Update docker network in a swarm cluster without downtime
  • after delete docker image, why can still find the deleted image by _catlog api?
  • Docker: Scaling Python container, memory overhead
  • 2 Solutions collect form web for “Docker creates files as root in mounted volume [duplicate]”

    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.)

    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
    Docker will be the best open platform for developers and sysadmins to build, ship, and run distributed applications.