容器化 Python 應用程式

先決條件

  • 您已安裝最新版本的 Docker Desktop
  • 您有一個 git 客戶端。本節中的示例使用基於命令列的 git 客戶端,但您可以使用任何客戶端。

概述

本節將引導您完成 Python 應用程式的容器化和執行。

獲取示例應用程式

示例應用程式使用流行的 FastAPI 框架。

克隆示例應用程式以配合本指南使用。開啟終端,將目錄更改到您要工作的目錄,然後執行以下命令克隆儲存庫:

$ git clone https://github.com/estebanx64/python-docker-example && cd python-docker-example

初始化 Docker 資產

現在您已經擁有一個應用程式,您可以建立必要的 Docker 資產來容器化您的應用程式。您可以使用 Docker Desktop 內建的 Docker Init 功能來簡化此過程,也可以手動建立資產。

python-docker-example 目錄下,執行 docker init 命令。 docker init 提供了一些預設配置,但您需要回答幾個關於應用程式的問題。例如,此應用程式使用 FastAPI 執行。參考以下示例回答 docker init 的提示,並使用相同的答案。

$ docker init
Welcome to the Docker Init CLI!

This utility will walk you through creating the following files with sensible defaults for your project:
  - .dockerignore
  - Dockerfile
  - compose.yaml
  - README.Docker.md

Let's get started!

? What application platform does your project use? Python
? What version of Python do you want to use? 3.12
? What port do you want your app to listen on? 8000
? What is the command to run your app? python3 -m uvicorn app:app --host=0.0.0.0 --port=8000

建立一個名為 .gitignore 的檔案,內容如下。

.gitignore
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

如果您沒有安裝 Docker Desktop 或更喜歡手動建立資產,您可以在專案目錄中建立以下檔案。

建立一個名為 Dockerfile 的檔案,內容如下。

Dockerfile
# syntax=docker/dockerfile:1

# Comments are provided throughout this file to help you get started.
# If you need more help, visit the Dockerfile reference guide at
# https://docs.docker.net.tw/go/dockerfile-reference/

# Want to help us make this template better? Share your feedback here: https://forms.gle/ybq9Krt8jtBL3iCk7

ARG PYTHON_VERSION=3.12
FROM python:${PYTHON_VERSION}-slim

# Prevents Python from writing pyc files.
ENV PYTHONDONTWRITEBYTECODE=1

# Keeps Python from buffering stdout and stderr to avoid situations where
# the application crashes without emitting any logs due to buffering.
ENV PYTHONUNBUFFERED=1

WORKDIR /app

# Create a non-privileged user that the app will run under.
# See https://docs.docker.net.tw/go/dockerfile-user-best-practices/
ARG UID=10001
RUN adduser \
    --disabled-password \
    --gecos "" \
    --home "/nonexistent" \
    --shell "/sbin/nologin" \
    --no-create-home \
    --uid "${UID}" \
    appuser

# Download dependencies as a separate step to take advantage of Docker's caching.
# Leverage a cache mount to /root/.cache/pip to speed up subsequent builds.
# Leverage a bind mount to requirements.txt to avoid having to copy them into
# into this layer.
RUN --mount=type=cache,target=/root/.cache/pip \
    --mount=type=bind,source=requirements.txt,target=requirements.txt \
    python -m pip install -r requirements.txt

# Switch to the non-privileged user to run the application.
USER appuser

# Copy the source code into the container.
COPY . .

# Expose the port that the application listens on.
EXPOSE 8000

# Run the application.
CMD ["python3", "-m", "uvicorn", "app:app", "--host=0.0.0.0", "--port=8000"]

建立一個名為 compose.yaml 的檔案,內容如下。

compose.yaml
# Comments are provided throughout this file to help you get started.
# If you need more help, visit the Docker Compose reference guide at
# https://docs.docker.net.tw/go/compose-spec-reference/

# Here the instructions define your application as a service called "server".
# This service is built from the Dockerfile in the current directory.
# You can add other services your application may depend on here, such as a
# database or a cache. For examples, see the Awesome Compose repository:
# https://github.com/docker/awesome-compose
services:
  server:
    build:
      context: .
    ports:
      - 8000:8000

建立一個名為 .dockerignore 的檔案,內容如下。

.dockerignore
# Include any files or directories that you don't want to be copied to your
# container here (e.g., local build artifacts, temporary files, etc.).
#
# For more help, visit the .dockerignore file reference guide at
# https://docs.docker.net.tw/go/build-context-dockerignore/

**/.DS_Store
**/__pycache__
**/.venv
**/.classpath
**/.dockerignore
**/.env
**/.git
**/.gitignore
**/.project
**/.settings
**/.toolstarget
**/.vs
**/.vscode
**/*.*proj.user
**/*.dbmdl
**/*.jfm
**/bin
**/charts
**/docker-compose*
**/compose.y*ml
**/Dockerfile*
**/node_modules
**/npm-debug.log
**/obj
**/secrets.dev.yaml
**/values.dev.yaml
LICENSE
README.md

建立一個名為 .gitignore 的檔案,內容如下。

.gitignore
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

現在,您的 python-docker-example 目錄中應該包含以下內容。

├── python-docker-example/
│ ├── app.py
│ ├── requirements.txt
│ ├── .dockerignore
│ ├── .gitignore
│ ├── compose.yaml
│ ├── Dockerfile
│ └── README.md

要了解有關這些檔案的更多資訊,請參閱以下內容

執行應用程式

python-docker-example 目錄中,在終端中執行以下命令。

$ docker compose up --build

開啟瀏覽器並訪問 https://:8000 檢視應用程式。您應該會看到一個簡單的 FastAPI 應用程式。

在終端中,按 ctrl+c 停止應用程式。

在後臺執行應用程式

您可以透過新增 -d 選項,將應用程式從終端分離執行。在 python-docker-example 目錄中,在終端中執行以下命令。

$ docker compose up --build -d

開啟瀏覽器並訪問 https://:8000

要檢視 OpenAPI 文件,您可以訪問 https://:8000/docs

您應該會看到一個簡單的 FastAPI 應用程式。

在終端中,執行以下命令以停止應用程式。

$ docker compose down

有關 Compose 命令的更多資訊,請參閱Compose CLI 參考

摘要

在本節中,您學習瞭如何使用 Docker 容器化並執行您的 Python 應用程式。

相關資訊

後續步驟

在下一節中,您將瞭解如何使用 Docker 容器設定本地開發環境。