將 Python 應用程式容器化
先決條件
- 您已安裝最新版本的 Docker Desktop。
- 您有一個 git 用戶端。本節中的範例使用基於命令列的 git 用戶端,但您可以使用任何用戶端。
概觀
本節將引導您完成 Python 應用程式的容器化和執行。
取得範例應用程式
範例應用程式使用熱門的 FastAPI 框架。
複製範例應用程式以搭配本指南使用。開啟終端機,將目錄變更為您想要使用的目錄,然後執行以下命令來複製儲存庫
$ git clone https://github.com/estebanx64/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.11.4
? 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
的檔案,其中包含以下內容。
# 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
的檔案,其中包含以下內容。
# 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://docker-docs.dev.org.tw/go/dockerfile-reference/
# Want to help us make this template better? Share your feedback here: https://forms.gle/ybq9Krt8jtBL3iCk7
ARG PYTHON_VERSION=3.11.4
FROM python:${PYTHON_VERSION}-slim AS base
# 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://docker-docs.dev.org.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
的檔案,其中包含以下內容。
# Comments are provided throughout this file to help you get started.
# If you need more help, visit the Docker Compose reference guide at
# https://docker-docs.dev.org.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
的檔案,其中包含以下內容。
# 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://docker-docs.dev.org.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
的檔案,其中包含以下內容。
# 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
開啟瀏覽器並在 http://localhost:8000檢視應用程式。您應該會看到一個簡單的 FastAPI 應用程式。
在終端機中,按下 ctrl
+c
以停止應用程式。
在背景執行應用程式
您可以透過新增 -d
選項,讓應用程式與終端機分離執行。在 python-docker-example
目錄中,於終端機中執行以下命令。
$ docker compose up --build -d
開啟瀏覽器並在 http://localhost:8000。
您應該會看到一個簡單的 FastAPI 應用程式。
在終端機中,執行以下命令以停止應用程式。
$ docker compose down
有關 Compose 命令的更多資訊,請參閱 Compose CLI 參考。
摘要
在本節中,您學習了如何使用 Docker 將 Python 應用程式容器化和執行。
相關資訊
後續步驟
在下一節中,您將學習如何使用容器開發您的應用程式。