[SOLVED] Docker does not mount volume as current user

Issue

This Content is from Stack Overflow. Question asked by Deniss Kozlovs

I have a website that I’m trying to run inside Docker container. To avoid file permission errors, I change the ID of user www-data to match my user id on host. This setup worked for me, but after some time it stopped working, and I cannot find reason why.

FROM php:7.4-fpm

ARG HOST_UID

# Not relevant lines skipped

RUN usermod -u $HOST_UID www-data
RUN groupmod -g $HOST_UID www-data

Then I build container with:

docker compose build --build-arg HOST_UID=$(id -u)

All files on host belong to my user:

enter image description here

After starting container, I can see that ID is changed:

enter image description here

However, inside container they belong to root:

enter image description here

Could this be because docker daemon runs as root and mounts the volume as such?



Solution

You should use the -u flag for docker compose run.

Here an example:

setup:

mkdir mihai
touch mihai/test.txt

docker-compose.yml

version: '3'

services:
  test:
    image: "alpine:latest"
    volumes:
      - "./mihai:/mihai"

Run normal

docker compose run test ls -l /mihai

gives output:

total 0
-rw-r--r--    1 root     root             0 Sep 18 11:39 test.txt

Run as user:

docker compose run -u "$(id -u):$(id -g)" test ls -l /mihai

gives output:

total 0
-rw-r--r--    1 501      dialout          0 Sep 18 11:39 test.txt

If you use a custom image where you actually declare user and group then you will see a nicer output than 501 and dialout.


This Question was asked in StackOverflow by Deniss Kozlovs and Answered by Mihai It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?