我使用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'有root用户和组。
我尝试在容器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所有权?
答案 0 :(得分:1)
如果你的useradd
工作,那么拼图的最后一部分就是切换到Dockerfile中的那个用户,以便在构建容器时运行特定的命令:
https://docs.docker.com/engine/reference/builder/#user
请注意,在docker-compose.yml中指定user: user
只会影响启动容器时运行的最终进程(即ENTRYPOINT
或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
将所有文件作为Dockerfile中的RUN
步骤运行:
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"]