11. 交付与运维
11.1 部署流程
部署架构
部署环境
- 开发环境(Dev):用于开发测试,资源较少
- 测试环境(Test):用于功能测试,资源适中
- 预发布环境(Staging):用于预发布验证,资源接近生产
- 生产环境(Prod):正式运行环境,资源充足,高可用
部署流程
容器化部署
Docker镜像构建
# Dockerfile示例
FROM python:3.11-slim
WORKDIR /app
# 安装依赖
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# 复制代码
COPY . .
# 设置环境变量
ENV PYTHONUNBUFFERED=1
# 暴露端口
EXPOSE 8000
# 启动命令
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
Kubernetes部署配置
# Kubernetes部署配置
apiVersion: apps/v1
kind: Deployment
metadata:
name: education-api
spec:
replicas: 3
selector:
matchLabels:
app: education-api
template:
metadata:
labels:
app: education-api
spec:
containers:
- name: api
image: education-api:latest
ports:
- containerPort: 8000
env:
- name: DATABASE_URL
valueFrom:
secretKeyRef:
name: db-secret
key: url
resources:
requests:
cpu: "500m"
memory: "1Gi"
limits:
cpu: "2000m"
memory: "4Gi"
livenessProbe:
httpGet:
path: /health
port: 8000
initialDelaySeconds: 30
periodSeconds: 10
readinessProbe:
httpGet:
path: /ready
port: 8000
initialDelaySeconds: 5
periodSeconds: 5
---
apiVersion: v1
kind: Service
metadata:
name: education-api-service
spec:
selector:
app: education-api
ports:
- protocol: TCP
port: 80
targetPort: 8000
type: LoadBalancer
CI/CD流程
GitHub Actions配置
# .github/workflows/deploy.yml
name: Deploy
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v1
- name: Login to Docker Hub
uses: docker/login-action@v1
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Build and push
uses: docker/build-push-action@v2
with:
context: .
push: true
tags: education-api:${{ github.sha }}
- name: Deploy to Kubernetes
uses: azure/k8s-deploy@v1
with:
manifests: k8s/
images: education-api:${{ github.sha }}
kubectl-version: 'latest'