3

我用 Docker Compose 创建了 Django 项目:

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

码头工人-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

它工作得很好。但是通过容器“django-project”创建的所有新文件都有根所有者和组。

我尝试user: user为容器添加 Compose 配置django-project。但有异常User user not found

我尝试user使用代码添加容器:

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

但异常仍然存在。

如何为将通过 docker 容器创建的所有新文件应用非 root 所有权?

4

1 回答 1

1

如果您useradd工作了,那么最后一个难题是在构建容器时切换到 Dockerfile 中的该用户以运行特定命令:
https ://docs.docker.com/engine/reference/builder/#user

请注意,user: user在 docker-compose.yml 中指定仅影响启动容器时运行的最终进程(即ENTRYPOINTor CMD
https://docs.docker.com/engine/reference/run/#user

所以你需要:

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

或者,您可以以root用户身份运行所有内容,但chown将所有文件作为RUNDockerfile 中的一个步骤运行:

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"]
于 2016-01-26T14:30:38.333 回答