Know Your Wisdom

Docker 构建 Django 镜像最佳实践

2022-04-09

本文介绍了在 Docker 中构建 Django 镜像的最佳实践,包括导出依赖项、创建 Dockerfile、安装系统包和应用服务器、复制项目源代码、收集静态文件以及运行时命令等步骤。

Refer docker doc

Create Docker Image

First, export dependencies: `pip freeze > requirements`.

Create a Dockerfile in the project root:

# Use an official Python runtime based on Debian 10 "buster" as a parent image.
FROM python:3.9.6-slim-buster

# Add user that will be used in the container.
RUN useradd cjh

# Port used by this container to serve HTTP.
EXPOSE 9090

# Set environment variables.
# 1. Force Python stdout and stderr streams to be unbuffered.
# 2. Set PORT variable that is used by Gunicorn. This should match "EXPOSE"
#    command.
ENV PYTHONUNBUFFERED=1 \
    PORT=9090

# Install system packages required by Wagtail and Django.
RUN apt-get update --yes --quiet && apt-get install --yes --quiet --no-install-recommends \
    build-essential \
    libpq-dev \
    libmariadbclient-dev \
    libjpeg62-turbo-dev \
    zlib1g-dev \
    libwebp-dev \
 && rm -rf /var/lib/apt/lists/*

# Install the application server.
RUN pip install "gunicorn==20.0.4"

# Install the project requirements.
COPY requirements.txt /
RUN pip install -r /requirements.txt

# Use /app folder as a directory where the source code is stored.
WORKDIR /app

# Set this directory to be owned by the "cjh" user. This Wagtail project
# uses SQLite, the folder needs to be owned by the user that
# will be writing to the database file.
RUN chown cjh:cjh /app

# Copy the source code of the project into the container.
COPY --chown=cjh:cjh . .

# Use user "cjh" to run the build commands below and the server itself.
USER cjh

# Collect static files.
RUN python manage.py collectstatic --noinput --clear

# Runtime command that executes when "docker run" is called, it does the
# following:
#   1. Migrate the database.
#   2. Start the application server.
# WARNING:
#   Migrating database at the same time as starting the server IS NOT THE BEST
#   PRACTICE. The database should be migrated manually or using the release
#   phase facilities of your hosting platform. This is used only so the
#   Wagtail instance can be started with a simple "docker run" command.
CMD set -xe; python manage.py migrate --noinput; gunicorn myweb3.wsgi:application

Build

docker build -t myweb3 .

Build