dockerdocker-compose

Docker-compose set user and group on mounted volume


I'm trying to mount a volume in docker-compose to apache image. The problem is, that apache in my docker is run under www-data:www-data but the mounted directory is created under root:root. How can I specify the user of the mounted directory?

I tried to run command setupApacheRights.sh. chown -R www-data:www-data /var/www but it says chown: changing ownership of '/var/www/somefile': Permission denied

services:
    httpd:
        image: apache-image
        ports:
            - "80:80"
        volumes:
            - "./:/var/www/app"
        links:
            - redis
        command: /setupApacheRights.sh

I would prefer to be able to specify the user under which it will be mounted. Is there a way?


Solution

  • First determine the uid of the www-data user:

    $ docker exec DOCKER_CONTAINER_ID id
    uid=100(www-data) gid=101(www-data) groups=101(www-data)
    

    Then, on your docker host, change the owner of the mounted directory using the uid (100 in this example):

    chown -R 100 ./
    

    Dynamic Extension

    If you are using docker-compose you may as well go for it like this:

    $ docker-compose exec SERVICE_NAME id
    uid=100(www-data) gid=101(www-data) groups=101(www-data)
    $ chown -R 100 ./
    

    You can put that in a one-liner:

    $ chown -R $(docker-compose exec SERVICE_NAME id -u) ./
    

    The -u flag will only print the uid to stdout.

    Edit: fixed casing error of CLI flag. Thanks @jcalfee314!