Skip to content

25.5 智慧部署

智慧部署概述

Claude Code 可以自動化部署流程、最佳化部署配置、監控部署狀態,並提供部署最佳化建議。透過智慧部署功能,開發者可以快速、安全地將應用部署到生產環境。

自动化部署

1. Docker 部署

示例:生成 Docker 部署配置

使用者請求: "為這個 Flask 應用生成 Docker 部署配置"

Claude Code 生成的配置:

python
## Dockerfile

    dockerfile


    ````dockerfile

    ````nginx

    events {
    worker_connections 1024;
    }

    http {
    upstream web {
    least_conn;
    server web:5000;
    }

     # 限流配置
    limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;

    server {
    listen 80;
    server_name example.com;

     # 重定向到 HTTPS
    return 301 https://$server_name$request_uri;
    }

    server {
    listen 443 ssl http2;
    server_name example.com;

    ssl_certificate /etc/nginx/ssl/cert.pem;
    ssl_certificate_key /etc/nginx/ssl/key.pem;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;

     # 日志配置
    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

     # 静态文件缓存
    location /static/ {
    alias /app/static/;
    expires 30d;
    add_header Cache-Control "public, immutable";
    }

     # API 限流
    location /api/ {
    limit_req zone=api_limit burst=20 nodelay;
    proxy_pass http://web;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    }

     # 健康检查
    location /health {
    proxy_pass http://web/health;
    access_log off;
    }

     # 默认代理
    location / {
    proxy_pass http://web;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    }
    }
    }

    ```## .dockerignore

    ```
    __pycache__
    > *.pyc
    > *.pyo
    > *.pyd
    .Python
    env/
    venv/
    ENV/
    .venv
    .git/
    .gitignore
    README.md
    Dockerfile
    docker-compose.yml
    nginx.conf
    .env
    > *.log
    tests/
    .pytest_cache/
    .coverage
    htmlcov/
    ## 部署脚本

    ```

    ``bash
    bash

    #!/bin/bash

    # rollback.sh - 回滚脚本

    set -e

    echo "开始回滚..."

    # 停止当前容器

    docker-compose down

    # 拉取上一个版本

    git checkout HEAD~1

    # 启动旧版本

    docker-compose up -d

    # 等待服务启动

    sleep 10

    # 健康检查

    if curl -f http://localhost:5000/health; then
        echo "回滚成功!"
    else
        echo "回滚失败!"
        docker-compose logs
        exit 1
    fi

    echo "回滚完成!"

    ### 2. Kubernetes 部署

    apiVersion: networking.k8s.io/v1
    kind: Ingress
    metadata:
    name: web-app-ingress
    annotations:
    cert-manager.io/cluster-issuer: "letsencrypt-prod"
    nginx.ingress.kubernetes.io/ssl-redirect: "true"
    nginx.ingress.kubernetes.io/rate-limit: "100"
    spec:
    ingressClassName: nginx
    tls:

     - hosts:
     - example.com

    secretName: web-app-tls
    rules:

     - host: example.com

    http:
    paths:

     - path: /

    pathType: Prefix
    backend:
    service:
    name: web-app-service
    port:
    number: 80

    ## configmap.yaml

    apiVersion: v1
    kind: Secret
    metadata:
    name: app-secrets
    type: Opaque
    stringData:
    database-url: "postgresql://user:password@postgres-service:5432/mydb"
    secret-key: "your-secret-key-here"

    ## postgres-deployment.yaml

    apiVersion: apps/v1
    kind: Deployment
    metadata:
    name: redis
    spec:
    replicas: 1
    selector:
    matchLabels:
    app: redis
    template:
    metadata:
    labels:
    app: redis
    spec:
    containers:

     - name: redis

    image: redis:7-alpine
    ports:

     - containerPort: 6379

    resources:
    requests:
    memory: "128Mi"
    cpu: "100m"
    limits:
    memory: "256Mi"
    cpu: "200m"
    > ---
    apiVersion: v1
    kind: Service
    metadata:
    name: redis-service
    spec:
    selector:
    app: redis
    ports:

     - port: 6379

    targetPort: 6379
    clusterIP: None

    ## 部署脚本

    python

    # 示例:实现健康检查

    用户请求:
    "为应用实现健康检查"

    Claude Code 生成的代码:

    from flask import Flask, jsonify
    import psutil
    import time
    from datetime import datetime

    app = Flask(__name__)

    # 健康状态

    health_status = {
        'status': 'healthy',
        'last_check': datetime.utcnow(),
        'checks': {}
    }

    @app.route('/health')
    def health_check():
        """健康检查端点"""
        checks = {
            'database': check_database(),
            'redis': check_redis(),
            'disk_space': check_disk_space(),
            'memory': check_memory()
        }

        all_healthy = all(check['status'] == 'ok' for check in checks.values())

        health_status['status'] = 'healthy' if all_healthy else 'unhealthy'
        health_status['last_check'] = datetime.utcnow()
        health_status['checks'] = checks

        status_code = 200 if all_healthy else 503

        return jsonify(health_status), status_code

    @app.route('/health/ready')
    def readiness_check():
        """就绪检查"""
        try:
            check_database()
            check_redis()
            return jsonify({'status': 'ready'}), 200
        except Exception as e:
            return jsonify({'status': 'not ready', 'error': str(e)}), 503

    @app.route('/health/live')
    def liveness_check():
        """存活检查"""
        return jsonify({'status': 'alive', 'timestamp': datetime.utcnow().isoformat()}), 200

    def check_database():
        """检查数据库连接"""
        try:
            from app import db
            db.session.execute('SELECT 1')
            return {'status': 'ok', 'message': 'Database connection successful'}
        except Exception as e:
            return {'status': 'error', 'message': str(e)}

    def check_redis():
        """检查 Redis 连接"""
        try:
            from app import redis
            redis.ping()
            return {'status': 'ok', 'message': 'Redis connection successful'}
        except Exception as e:
            return {'status': 'error', 'message': str(e)}

    def check_disk_space():
        """检查磁盘空间"""
        disk = psutil.disk_usage('/')
        free_percent = (disk.free / disk.total) * 100

        if free_percent < 10:
            return {
                'status': 'error',
                'message': f'Low disk space: {free_percent:.1f}% free'
            }

        return {
            'status': 'ok',
            'message': f'Disk space: {free_percent:.1f}% free'
        }

    def check_memory():
        """检查内存使用"""
        memory = psutil.virtual_memory()
        used_percent = memory.percent

        if used_percent > 90:
            return {
                'status': 'error',
                'message': f'High memory usage: {used_percent:.1f}%'
            }

        return {
            'status': 'ok',
            'message': f'Memory usage: {used_percent:.1f}%'
        }

    if __name__ == '__main__':
        app.run(host='0.0.0.0', port=5000)

    ### 2. 日志监控

    `dockerfile

    # 多阶段构建

    FROM python:3.11-slim as builder

    WORKDIR /app

    # 安装构建依赖

    RUN apt-get update && apt-get install -y gcc

    # 复制依赖文件

    COPY requirements.txt .

    # 安装 Python 依赖

    RUN pip install --user --no-cache-dir -r requirements.txt

    # 运行时镜像

    FROM python:3.11-slim

    WORKDIR /app

    # 从构建阶段复制依赖

    COPY --from=builder /root/.local /root/.local

    # 复制应用代码

    COPY . .

    # 设置 PATH

    ENV PATH=/root/.local/bin:$PATH

    # 创建非 root 用户

    RUN useradd -m appuser && chown -R appuser:appuser /app
    USER appuser

    # 暴露端口

    EXPOSE 5000

    # 启动应用

    CMD ["gunicorn", "--bind", "0.0.0.0:5000", "--workers", "4", "--threads", "2", "app:app"]

    python

    # gunicorn_config.py

    import multiprocessing

    # 工作进程数

    workers = multiprocessing.cpu_count() * 2 + 1

    # 线程数

    threads = 2

    # 工作模式

    worker_class = 'gevent'

    # 工作进程连接数

    worker_connections = 1000

    # 超时时间

    timeout = 30
    keepalive = 2

    # 最大请求数

    max_requests = 1000
    max_requests_jitter = 50

    # 日志配置

    accesslog = '-'
    errorlog = '-'
    loglevel = 'info'

    # 预加载应用

    preload_app = True

    # 进程名称

    proc_name = 'web-app'

    > **优化效果**:
    > - 吞吐量提高 50%
    > - 响应时间减少 40%
    > - 资源利用率提高 30%

    ### 3. 数据库连接池优化

    # config.py

    from sqlalchemy import create_engine
    from sqlalchemy.pool import QueuePool

    engine = create_engine(
    DATABASE_URL,
    poolclass=QueuePool,
    pool_size=20,
    max_overflow=40,
    pool_timeout=30,
    pool_recycle=3600,
    pool_pre_ping=True,
    echo=False
    )

    ```> **优化效果**:
    > - 数据库连接数减少 60%
    > - 查询响应时间减少 30%
    > - 连接池效率提高 50%

    ```

    ### 2. 成本最佳化

    # 示例:最佳化部署成本

    使用者請求:
    "最佳化應用部署成本"
    Claude Code 生成的最佳化建議:

    ## 部署成本最佳化

    ### 1. 資源最佳化

    #### Kubernetes 資源配置

    ````yaml
    `yaml

    apiVersion: apps/v1
    kind: Deployment
    metadata:
    name: web-app
    spec:
    replicas: 3
    template:
    spec:
    containers:
     - name: web-app
    resources:
    requests:
    memory: "128Mi"
    cpu: "100m"
    limits:
    memory: "256Mi"
    cpu: "200m"

    ```> **最佳化效果**:

    > - 資源成本降低 50%
    > - 資源利用率提高 40%

    ### 2. 自動擴縮容

    ```
    yaml

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

    > **优化效果**:
    > - 成本降低 30%
    > - 资源利用率提高 50%

    ### 3. 节点亲和性

    ````yaml

    > - 成本降低 60%
    > - 使用 Spot 实例

基于 MIT 许可发布 | 永久导航