Search code examples
djangodocker-composefile-ownership

Docker compose file ownership


I created Django project with Docker Compose:

Dockerfile

FROM python:2.7

ENV PYTHONUNBUFFERED 1

RUN mkdir /code
WORKDIR /code
ADD . /code/

RUN pip install -r requirements.txt

WORKDIR /code/example
ENTRYPOINT ["python", "manage.py"]

docker-compose.yml

postgres:
  image: postgres
  ports:
  - '5432:5432'

django-project:
  build: .
  command: runserver 0.0.0.0:8000
  volumes:
  - .:/code
  ports:
  - '8000:8000'
  links:
  - postgres

It work nice. But all new files which create through container 'django-project' have root owner and group.

I try add user: user in Compose config for container django-project. But got exception User user not found.

I try add user in container with code:

ENV HOME_USER user
ENV HOME_PASS password

RUN useradd -m -s /bin/bash ${HOME_USER} && \
    echo "${HOME_USER}:${HOME_PASS}"|chpasswd && \
    adduser ${HOME_USER} sudo && \
    echo ${HOME_USER}' ALL=(ALL) NOPASSWD: ALL' >> /etc/sudoers

But exception stayed.

How I can apply non-root ownership for all new files which will create through docker container?


Solution

  • if your useradd worked then the last piece of the puzzle is to switch to that user in the Dockerfile to run particular commands when the container is built:
    https://docs.docker.com/engine/reference/builder/#user

    Note that specifying user: user in the docker-compose.yml only affects the final process that's run when you start the container (i.e. the ENTRYPOINT or CMD)
    https://docs.docker.com/engine/reference/run/#user

    So you need to:

    FROM python:2.7
    
    ENV PYTHONUNBUFFERED 1
    
    ENV HOME_USER user
    ENV HOME_PASS password
    
    RUN useradd -m -s /bin/bash ${HOME_USER} && \
        echo "${HOME_USER}:${HOME_PASS}"|chpasswd && \
        adduser ${HOME_USER} sudo && \
        echo ${HOME_USER}' ALL=(ALL) NOPASSWD: ALL' >> /etc/sudoers
    
    USER user
    
    RUN mkdir /code
    WORKDIR /code
    ADD . /code/
    
    RUN pip install -r requirements.txt
    
    WORKDIR /code/example
    ENTRYPOINT ["python", "manage.py"]
    

    Alternatively you could run everything as root user but chown all the files as a RUN step in the Dockerfile:

    FROM python:2.7
    
    ENV PYTHONUNBUFFERED 1
    
    ENV HOME_USER user
    ENV HOME_PASS password
    
    RUN useradd -m -s /bin/bash ${HOME_USER} && \
        echo "${HOME_USER}:${HOME_PASS}"|chpasswd && \
        adduser ${HOME_USER} sudo && \
        echo ${HOME_USER}' ALL=(ALL) NOPASSWD: ALL' >> /etc/sudoers
    
    RUN mkdir /code
    WORKDIR /code
    ADD . /code/
    
    RUN chown -R user /code
    
    RUN pip install -r requirements.txt
    
    WORKDIR /code/example
    ENTRYPOINT ["python", "manage.py"]