首页 > 解决方案 > 从 django 的 Docker 映像的 collectstatic 部分制作静态文件

问题描述

我想包含从python manage.py collectstaticDocker 映像中生成的静态文件。

为此,我在我的Dockerfile

CMD python manage.py collectstatic --no-input

但由于它在中间容器中运行命令,因此生成的静态文件不在STATIC_ROOT目录中。我可以在构建日志中看到以下几行。

Step 13/14 : CMD python manage.py collectstatic --no-input
 ---> Running in 8ea5efada461
Removing intermediate container 8ea5efada461
 ---> 67aef71cc7b6

我想在图像中包含生成的静态文件。我该怎么做才能实现这一目标?

更新(解决方案)

我正在使用 CMD 但相反,我应该使用 RUN 命令来执行此任务,正如文档所说

The RUN instruction will execute any commands in a new layer on top of the current image and commit the results. The resulting committed image will be used for the next step in the Dockerfile.

标签: djangodockerdockerfiledjango-staticfiles

解决方案


您需要将输出复制collectstatic到最终容器中。

例如,我的 dockerfile 包含相同的概念(这不是完整的 dockerfile,只是相关的部分)

# Pull base image
FROM python:3.7.7-slim-buster AS python-base

COPY requirements.txt /requirements.txt

WORKDIR /project
RUN apt-get update && \
    apt-get -y upgrade && \
    pip install --upgrade pip && \
    pip install -r /requirements.txt

FROM node:8 AS frontend-deps-npm
WORKDIR /
COPY ./package.json /package.json
RUN npm install
COPY . /app
WORKDIR /app
RUN /node_modules/gulp/bin/gulp.js


FROM python-base AS frontend-deps
COPY --from=frontend-deps-npm /app /app
WORKDIR /app
RUN python manage.py collectstatic -v 2 --noinput


FROM python-base AS app
COPY . /app
COPY --from=frontend-deps /app/static-collection /app/static-collection

推荐阅读