» Python:使用Kafka构建事件驱动微服务 » 5. 部署 » 5.1 Dockerfile

Dockerfile

Docker 允许开发人员将他们的应用程序以及所有依赖项打包成一个称为容器的单个单元。这确保了在不同环境(如开发、测试和生产)之间的一致性,减少了“但是它在我的机器上运行正常”的问题。

安装 Docker: https://docs.docker.com/engine/install/

web 服务的 Dockerfile

添加 service/web/Dockerfile:

# Use Alpine Linux with Python 3 as base image
FROM python:3.12.3-alpine3.19

RUN apk add --no-cache gcc libc-dev librdkafka-dev

# Set the working directory in the container
WORKDIR /app

# Copy the dependencies file to the working directory
COPY requirements.txt .

# Install dependencies
RUN pip install --no-cache-dir -r requirements.txt

# Copy the current directory contents into the container at /app
COPY service/ /app/service

CMD ["uvicorn", "service.web.main:app", "--host", "0.0.0.0", "--port", "8000"]

添加 service/web/.dockerignore:

# Ignore Python cache directories
**/__pycache__

config.yml

Alpine Linux 是一个轻量级的安全的 Linux 发行版,特别适用于容器化环境、嵌入式系统和资源受限环境。这些环境下效率和安全性至关重要。

为 web 服务构建 docker 镜像:

docker build -t lrbooks_web_py:latest -f service/web/Dockerfile .

相似地,添加另外 2 个 Dockerfiles:

热搜服务的 Dockerfile

添加 service/trend/Dockerfile:

# Use Alpine Linux with Python 3 as base image
FROM python:3.12.3-alpine3.19

RUN apk add --no-cache gcc libc-dev librdkafka-dev

# Set the working directory in the container
WORKDIR /app

# Copy the dependencies file to the working directory
COPY requirements.txt .

# Install dependencies
RUN pip install --no-cache-dir -r requirements.txt

# Copy the current directory contents into the container at /app
COPY service/ /app/service

CMD ["uvicorn", "service.trend.main:app", "--host", "0.0.0.0", "--port", "8001"]

添加 service/trend/.dockerignore:

# Ignore Python cache directories
**/__pycache__

config.yml

推荐服务的 Dockerfile

添加 service/recommendation/Dockerfile:

# Use Alpine Linux with Python 3 as base image
FROM python:3.12.3-alpine3.19

RUN apk add --no-cache gcc libc-dev librdkafka-dev

# Set the working directory in the container
WORKDIR /app

# Copy the dependencies file to the working directory
COPY requirements.txt .

# Install dependencies
RUN pip install --no-cache-dir -r requirements.txt

# Copy the current directory contents into the container at /app
COPY service/ /app/service

CMD ["uvicorn", "service.recommendation.main:app", "--host", "0.0.0.0", "--port", "8002"]

添加 service/recommendation/.dockerignore:

# Ignore Python cache directories
**/__pycache__

config.yml

准备好所有 Dockerfile 之后,就可以在 Docker Compose 里启动所有服务了。

上页下页