luqo33
luqo33

Reputation: 8361

Docker: mounting local directories as a non-root user in a container

I've read quite a few threads on the internet about how to best mount local (project) directories into a Docker container so that the directories are not owned by the root user. Unfortunately, I've not found a precise answer.

I'm building my development stack with this docker-compose.yml (SfDocker) file:

db:
    image: mysql:latest
    ports:
    - "3306:3306"
    environment:
        MYSQL_ROOT_PASSWORD: symfonyrootpass
        MYSQL_DATABASE: symfony
        MYSQL_USER: symfony
        MYSQL_PASSWORD: symfonypass
worker:
    image: symfony/worker-dev
    ports:
    - "8080:80"
    environment:
        XDEBUG_HOST: 192.168.1.194
        XDEBUG_PORT: 9000
        XDEBUG_REMOTE_MODE: req
    links:
    - db
    volumes:
    - "var/nginx/:/var/log/nginx"
    - symfony-code:/var/www/app

Volumes are mounted at runtime only after the images are built. I've added a new user by RUN groupadd -r luqo33 && useradd -r -g luqo33 luqo33 in the symfony/worker-dev image, but I was not able to chmod the mounted volumes so that it is owned by luqo33:www-data. I've tried to do it by:

  1. Copying and running an entrypoint.sh with chmod command:

    COPY entrypoint.sh /entrypoint.sh RUN chmod +x /entrypoint.sh ENTRYPOINT ["/entrypoint.sh"]

The container would start and then shut down with no apparent reason.

  1. Executing CMD chown -R luqo33:www-data while starting containers - this could not work because at the time of starting the worker-dev container, the volumes seem not to be mounted yet.

I did not manage to set the ownership of the mounted directories to users other than root. How can I achieve this?

Upvotes: 3

Views: 2217

Answers (1)

Adrian Mouat
Adrian Mouat

Reputation: 46518

You seem to be a bit confused about how Docker works, especially with regard to entrypoint and cmd scripts.

Any script referenced in an ENTRYPOINT or CMD instruction will be executed by the container at run-time. Once the script finishes, the container will exit. For this reason, you will need to both run your chmod and start the application in the script.

If the current user is root, a script like the following should work fine to set permissions and start the app:

#!/bin/bash

chown -R luqo33:www-data /var/www/app
sudo -u luqo33 exec start-my-app-in-foreground-script-or-bin

There is a slight problem with sudo creating two processes however, so you may want to use gosu instead.

Upvotes: 1

Related Questions