使用容器进行 Python 开发
先决条件
概述
在本节中,您将学习如何为容器化应用程序设置开发环境。这包括
- 添加本地数据库并持久化数据
- 配置 Compose 在您编辑和保存代码时自动更新正在运行的 Compose 服务
获取示例应用程序
你需要克隆一个新的仓库来获取一个包含连接数据库逻辑的示例应用程序。
切换到你想要克隆仓库的目录,然后运行以下命令。
$ git clone https://github.com/estebanx64/python-docker-dev-example在克隆的仓库目录中,手动创建 Docker 资产或运行 `docker init` 来创建必要的 Docker 资产。
在克隆的仓库目录中,运行 `docker init`。请参考以下示例,回答 `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? 8001 ? What is the command to run your app? python3 -m uvicorn app:app --host=0.0.0.0 --port=8001创建一个名为 `.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.container.net.cn/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.container.net.cn/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 8001 # Run the application. CMD ["python3", "-m", "uvicorn", "app:app", "--host=0.0.0.0", "--port=8001"]创建一个名为
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.container.net.cn/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: - 8001:8001 # The commented out section below is an example of how to define a PostgreSQL # database that your application can use. `depends_on` tells Docker Compose to # start the database before your application. The `db-data` volume persists the # database data between container restarts. The `db-password` secret is used # to set the database password. You must create `db/password.txt` and add # a password of your choosing to it before running `docker compose up`. # depends_on: # db: # condition: service_healthy # db: # image: postgres # restart: always # user: postgres # secrets: # - db-password # volumes: # - db-data:/var/lib/postgresql/data # environment: # - POSTGRES_DB=example # - POSTGRES_PASSWORD_FILE=/run/secrets/db-password # expose: # - 5432 # healthcheck: # test: [ "CMD", "pg_isready" ] # interval: 10s # timeout: 5s # retries: 5 # volumes: # db-data: # secrets: # db-password: # file: db/password.txt创建一个名为
.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.container.net.cn/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/
添加本地数据库并持久化数据
您可以使用容器设置本地服务,例如数据库。在本节中,您将更新 compose.yaml 文件以定义数据库服务和用于持久化数据的卷。
在克隆的仓库目录中,使用 IDE 或文本编辑器打开 `compose.yaml` 文件。 `docker init` 处理了大部分指令的创建,但你需要根据你的独特应用程序进行更新。
在 `compose.yaml` 文件中,你需要取消注释所有数据库指令。此外,你需要将数据库密码文件作为环境变量添加到服务器服务,并指定要使用的 secret 文件。
以下是更新后的 `compose.yaml` 文件。
services:
server:
build:
context: .
ports:
- 8001:8001
environment:
- POSTGRES_SERVER=db
- POSTGRES_USER=postgres
- POSTGRES_DB=example
- POSTGRES_PASSWORD_FILE=/run/secrets/db-password
depends_on:
db:
condition: service_healthy
secrets:
- db-password
db:
image: postgres
restart: always
user: postgres
secrets:
- db-password
volumes:
- db-data:/var/lib/postgresql/data
environment:
- POSTGRES_DB=example
- POSTGRES_PASSWORD_FILE=/run/secrets/db-password
expose:
- 5432
healthcheck:
test: ["CMD", "pg_isready"]
interval: 10s
timeout: 5s
retries: 5
volumes:
db-data:
secrets:
db-password:
file: db/password.txt注意要了解有关 Compose 文件中指令的更多信息,请参阅Compose 文件参考。
在使用 Compose 运行应用程序之前,请注意此 Compose 文件指定了一个 `password.txt` 文件来存储数据库密码。你必须创建此文件,因为它未包含在源代码仓库中。
在克隆的仓库目录中,创建一个名为 `db` 的新目录,并在该目录中创建一个名为 `password.txt` 的文件,其中包含数据库密码。使用你喜欢的 IDE 或文本编辑器,将以下内容添加到 `password.txt` 文件中。
mysecretpassword保存并关闭 `password.txt` 文件。
你的 `python-docker-dev-example` 目录现在应该包含以下内容。
├── python-docker-dev-example/
│ ├── db/
│ │ └── password.txt
│ ├── app.py
│ ├── config.py
│ ├── requirements.txt
│ ├── .dockerignore
│ ├── .gitignore
│ ├── compose.yaml
│ ├── Dockerfile
│ ├── README.Docker.md
│ └── README.md现在,运行以下 `docker compose up` 命令来启动你的应用程序。
$ docker compose up --build
现在测试你的 API 端点。打开一个新终端,然后使用 curl 命令向服务器发出请求。
让我们用 POST 方法创建一个对象。
$ curl -X 'POST' \
'https://:8001/heroes/' \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"id": 1,
"name": "my hero",
"secret_name": "austing",
"age": 12
}'
您应该收到以下响应
{
"age": 12,
"id": 1,
"name": "my hero",
"secret_name": "austing"
}让我们用下一个 curl 命令发起 GET 请求。
curl -X 'GET' \
'https://:8001/heroes/' \
-H 'accept: application/json'
你应该收到与上面相同的响应,因为数据库中只有这一个对象。
{
"age": 12,
"id": 1,
"name": "my hero",
"secret_name": "austing"
}在终端中按 ctrl+c 停止您的应用程序。
自动更新服务
使用 Compose Watch 在您编辑和保存代码时自动更新正在运行的 Compose 服务。有关 Compose Watch 的更多详细信息,请参阅使用 Compose Watch。
在 IDE 或文本编辑器中打开 `compose.yaml` 文件,然后添加 Compose Watch 指令。以下是更新后的 `compose.yaml` 文件。
services:
server:
build:
context: .
ports:
- 8001:8001
environment:
- POSTGRES_SERVER=db
- POSTGRES_USER=postgres
- POSTGRES_DB=example
- POSTGRES_PASSWORD_FILE=/run/secrets/db-password
depends_on:
db:
condition: service_healthy
secrets:
- db-password
develop:
watch:
- action: rebuild
path: .
db:
image: postgres
restart: always
user: postgres
secrets:
- db-password
volumes:
- db-data:/var/lib/postgresql/data
environment:
- POSTGRES_DB=example
- POSTGRES_PASSWORD_FILE=/run/secrets/db-password
expose:
- 5432
healthcheck:
test: ["CMD", "pg_isready"]
interval: 10s
timeout: 5s
retries: 5
volumes:
db-data:
secrets:
db-password:
file: db/password.txt运行以下命令,使用 Compose Watch 运行您的应用程序。
$ docker compose watch
在终端中,通过 curl 请求应用程序以获取响应。
$ curl https://:8001
Hello, Docker!
您对本地机器上应用程序源文件的任何更改现在将立即反映在运行中的容器中。
在 IDE 或文本编辑器中打开 `python-docker-dev-example/app.py`,并通过添加几个感叹号来更新 `Hello, Docker!` 字符串。
- return 'Hello, Docker!'
+ return 'Hello, Docker!!!'
保存对 `app.py` 的更改,然后等待几秒钟,直到应用程序重新构建。再次通过 curl 请求应用程序,并验证更新后的文本是否出现。
$ curl https://:8001
Hello, Docker!!!
在终端中按 ctrl+c 停止您的应用程序。
摘要
在本节中,你了解了如何设置 Compose 文件以添加本地数据库并持久化数据。你还学习了如何使用 Compose Watch 在更新代码时自动重建并运行容器。
相关信息
后续步骤
在下一节中,你将学习如何设置 linting、格式化和类型检查,以遵循 Python 应用程序的最佳实践。