Docker compose file ownership

你。 提交于 2021-02-09 11:58:08

问题


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?


回答1:


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"]


来源:https://stackoverflow.com/questions/35008744/docker-compose-file-ownership

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!