使用容器进行Python开发
先决条件
完成 将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.11.4 ? 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.docker.com/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://docs.docker.com/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.docker.com/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.docker.com/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文件中,您需要取消所有数据库指令的注释。此外,您需要将数据库密码文件作为环境变量添加到服务器服务中,并指定要使用的密钥文件。
以下是更新后的 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' \
'http://localhost: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' \
'http://localhost: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 http://localhost:8001
Hello, Docker!
现在,您本地机器上应用程序源文件的任何更改将立即反映在运行的容器中。
在IDE或文本编辑器中打开python-docker-dev-example/app.py,并通过添加更多感叹号来更新Hello, Docker!字符串。
- return 'Hello, Docker!'
+ return 'Hello, Docker!!!'
将更改保存到app.py,然后等待几秒钟让应用程序重新构建。再次curl应用程序并验证更新的文本是否出现。
$ curl http://localhost:8001
Hello, Docker!!!
在终端中按下 ctrl+c 来停止你的应用程序。
摘要
在本节中,您了解了如何设置Compose文件以添加本地数据库并持久化数据。您还学习了如何使用Compose Watch在更新代码时自动重建和运行容器。
相关信息:
下一步
在下一节中,您将了解如何使用GitHub Actions设置CI/CD管道。