跳转至

Ch15 §05 部署与 DevOps · 讲解稿

章节定位: Ch15 生产层。教"如何把代码部署到生产": Docker / K8s / CI/CD / 监控 / AI 服务化。 承接: §04 测试 → §05 部署 走向: Ch17 AI 推理 / Ch18 ML 系统设计 篇幅: ~3700 字 / 阅读 11 分钟 / 讲解 22-25 分钟


一 · 一句话总览

DevOps = 代码 → 生产的全链路: Docker (容器化) + K8s (编排) + CI/CD (自动化) + 监控 (Prometheus/Grafana) + AI 服务化 (vLLM/TGI)。AI 工程师的"最后一公里"。


二 · 章节主线 (5 段)

第 1 段 · Docker 容器化 (8 分钟)

3.1.1 镜像 vs 容器

  • 镜像: 只读模板 (类 = 类)
  • 容器: 镜像运行实例 (类 = 对象)

3.1.2 Dockerfile

# 多阶段构建
FROM python:3.11-slim AS builder
WORKDIR /build
COPY requirements.txt .
RUN pip wheel --no-cache-dir --wheel-dir /wheels -r requirements.txt

FROM python:3.11-slim
WORKDIR /app
COPY --from=builder /wheels /wheels
COPY requirements.txt .
RUN pip install --no-cache-dir --no-index --find-links=/wheels -r requirements.txt
COPY src/ ./src/
EXPOSE 8000
CMD ["uvicorn", "src.api:app", "--host", "0.0.0.0", "--port", "8000"]

3.1.3 关键指令

指令 用途
FROM 基础镜像
RUN 执行命令
COPY 拷贝文件
WORKDIR 工作目录
ENV 环境变量
EXPOSE 暴露端口
CMD 启动命令

3.1.4 Docker 命令

docker build -t myapp:v1 .           # 构建
docker run -d -p 8000:8000 myapp    # 运行
docker ps                            # 查看运行中
docker logs -f <container>          # 日志
docker exec -it <container> bash    # 进入
docker stop <container>             # 停止
docker rm <container>               # 删除
docker images                        # 看镜像
docker push myapp:v1                # 推送

3.1.5 持久化

docker run -v /data:/mnt myapp     # bind mount
docker volume create mydata        # volume
docker run -v mydata:/data myapp   # 用 volume

第 2 段 · Kubernetes 编排 (10 分钟)

3.2.1 核心对象

对象 用途
Pod 1+ 容器, 共享网络/存储
Deployment 管理 Pod 副本
Service 暴露 Pod
ConfigMap 配置
Secret 敏感配置
Ingress 外部路由
StatefulSet 有状态 (DB)

3.2.2 Pod 示例

apiVersion: v1
kind: Pod
metadata:
  name: llm-pod
spec:
  containers:
  - name: llm
    image: myreg/llm:v1
    resources:
      limits:
        nvidia.com/gpu: 1
        memory: 32Gi
        cpu: "8"
    ports:
    - containerPort: 8000

3.2.3 Deployment

apiVersion: apps/v1
kind: Deployment
metadata:
  name: llm-server
spec:
  replicas: 3
  selector:
    matchLabels:
      app: llm
  template:
    metadata:
      labels:
        app: llm
    spec:
      containers:
      - name: llm
        image: myreg/llm:v1
        resources:
          limits:
            nvidia.com/gpu: 1

3.2.4 Service

apiVersion: v1
kind: Service
metadata:
  name: llm-service
spec:
  selector:
    app: llm
  ports:
  - port: 80
    targetPort: 8000
  type: LoadBalancer

3.2.5 自动扩缩 (HPA)

apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: llm-hpa
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: llm-server
  minReplicas: 2
  maxReplicas: 10
  metrics:
  - type: Resource
    resource:
      name: cpu
      target:
        type: Utilization
        averageUtilization: 70

3.2.6 kubectl 命令

kubectl get pods
kubectl describe pod <name>
kubectl logs -f <pod>
kubectl apply -f deployment.yaml
kubectl delete -f deployment.yaml
kubectl exec -it <pod> -- bash
kubectl rollout status deployment/llm-server

第 3 段 · CI/CD (10 分钟)

3.3.1 GitHub Actions

name: Build and Deploy

on:
  push:
    branches: [main]
  pull_request:

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v4
    - uses: actions/setup-python@v5
      with:
        python-version: '3.11'
        cache: 'pip'
    - run: pip install -e ".[dev]"
    - run: ruff check .
    - run: mypy src/
    - run: pytest --cov --cov-fail-under=80

  build:
    needs: test
    runs-on: ubuntu-latest
    if: github.ref == 'refs/heads/main'
    steps:
    - uses: actions/checkout@v4
    - uses: docker/setup-buildx-action@v3
    - uses: docker/login-action@v3
      with:
        registry: ghcr.io
        username: github.actor
        password: secrets.GITHUB_TOKEN
    - uses: docker/build-push-action@v5
      with:
        push: true
        tags: ghcr.io/github.repository:latest

3.3.2 GitOps

Git 是单一真相, 部署自动同步:

Developer → Git commit → ArgoCD → K8s

工具: ArgoCD, Flux。

3.3.3 发布策略

策略 描述
蓝绿 两套环境, 切流量
金丝雀 5% → 50% → 100%
A/B 测试 不同用户看不同版本
灰度 按地域 / 用户群

3.3.4 监控与告警

工具 用途
Prometheus 指标收集
Grafana 可视化
Loki 日志
Tempo Trace
AlertManager 告警

3.3.5 关键指标 (SLO)

指标 含义
延迟 p50 / p95 / p99
吞吐 RPS
错误率 5xx / 4xx
可用性 uptime%

第 4 段 · LLM 服务化 (8 分钟)

3.4.1 推理引擎

引擎 特点
vLLM PagedAttention, 高吞吐
TGI (HF) Rust + Python
TensorRT-LLM NVIDIA 极致
SGLang RadixAttention
Llama.cpp CPU / 边缘

3.4.2 vLLM 部署

python -m vllm.entrypoints.openai.api_server \
    --model meta-llama/Llama-2-7b-hf \
    --tensor-parallel-size 1 \
    --max-model-len 4096 \
    --gpu-memory-utilization 0.9

OpenAI 兼容 API。

3.4.3 FastAPI + vLLM

from fastapi import FastAPI
from vllm import LLM, SamplingParams

app = FastAPI()
llm = LLM(model="llama-2-7b")

@app.post("/generate")
async def generate(prompt: str, max_tokens: int = 256):
    params = SamplingParams(max_tokens=max_tokens)
    output = llm.generate([prompt], params)
    return {"text": output[0].outputs[0].text}

3.4.4 量化部署

# GPTQ / AWQ / bitsandbytes
from transformers import AutoModelForCausalLM
import bitsandbytes as bnb

model = AutoModelForCausalLM.from_pretrained(
    "llama-2-70b",
    load_in_4bit=True,  # INT4 量化
    device_map="auto"
)

70B 模型: FP16 140GB → INT4 35GB, 单 H100 (80GB) 可装。

3.4.5 服务监控

from prometheus_client import Counter, Histogram

REQUEST_COUNT = Counter("llm_request_total", "Total requests")
LATENCY = Histogram("llm_latency_seconds", "Request latency")

@app.post("/generate")
async def generate(prompt: str):
    REQUEST_COUNT.inc()
    with LATENCY.time():
        output = llm.generate([prompt])
    return output

第 5 段 · 实践与陷阱 (8 分钟)

3.5.1 ML 流水线

Data → Validate → Train → Evaluate → Deploy → Monitor
                                          ↓
                                       Retrain

工具: Kubeflow, Argo Workflows, Metaflow。

3.5.2 模型版本管理

工具 用途
MLflow 实验追踪 + 模型 registry
DVC 数据 + 模型版本
Weights & Biases 实验 + 监控
BentoML 模型打包 + 服务化

3.5.3 特征存储

工具 特点
Feast 主流, 离线 / 在线
Tecton 商业
Hopsworks 学术友好

3.5.4 边缘部署

  • Llama.cpp + 量化
  • ONNX Runtime
  • TensorRT
  • NVIDIA Jetson
  • 浏览器: WebLLM (WASM)

3.5.5 常见陷阱

  1. Docker 镜像太大: 多阶段 + slim base
  2. K8s 资源限制缺: 节点抖动
  3. 无 CI cache: 慢 10×
  4. 无健康检查: 服务挂掉不切流量
  5. 无 graceful shutdown: SIGTERM 不响应

三 · 易错点 (5 条)

  1. Docker 镜像缓存: 用 --no-cache-dir pip 装包。
  2. K8s liveness vs readiness: liveness 杀, readiness 流量切换。
  3. CI secrets: 永远用 GitHub Secrets, 别 hardcode。
  4. HPA 误扩: 设 minReplicas 防止下零。
  5. GPU 调度: K8s 需 NVIDIA device plugin。

四 · 跨章连接

章节 关联
Ch13 §04 并发 K8s Pod 调度
Ch14 §04 算法 性能测试
Ch07 §04 Transformer 模型部署
Ch17 §02 LLM 推理 vLLM / TGI

五 · 自测 5 题

  1. Docker 镜像 vs 容器?
  2. K8s Pod / Deployment / Service 关系?
  3. GitOps 核心?
  4. 金丝雀 vs 蓝绿?
  5. vLLM 优势?

六 · 一句话总结

DevOps = 代码到生产的全链路。Docker (容器) + K8s (编排) + CI/CD (自动化) + 监控 (可观测) + AI 服务化 (vLLM)。Ch15 至此讲完 — Linux/Git/代码设计/测试/DevOps, 是 AI 工程师"工程素养"。


七 · 板书建议

[板书 1: Docker]
   镜像 = 类, 容器 = 对象
   多阶段构建

[板书 2: K8s]
   Pod / Deployment / Service
   HPA 自动扩缩

[板书 3: CI/CD]
   lint + test + build + push
   GitOps 单一真相

[板书 4: LLM 服务化]
   vLLM + FastAPI + Docker + K8s

八 · 参考资料

  1. Docker 官方文档
  2. Kubernetes 官方文档
  3. GitHub Actions 文档
  4. vLLM 文档
  5. Ch17 §02 LLM 推理 (本套书)