nkds

导航

 

MonkeyCode部署架构详解:从单机到集群的完整方案

引言

MonkeyCode作为一款支持完全开源和私有化部署的AI编程助手,其最大的优势之一就是灵活的部署架构。无论你是5人的初创团队,还是5000人的大型企业,MonkeyCode都能提供匹配的部署方案。本文将系统介绍从单机开发到生产级集群的完整部署架构。

部署架构总览

┌─────────────────────────────────────────────────────────────┐
│           MonkeyCode 部署架构演进路径                          │
│                                                             │
│  Level 1: 单机开发环境                                       │
│  ┌─────────────────────────┐                                │
│  │  1台工作站 + GPU        │  适用:<10人团队/POC验证         │
│  └──────────┬──────────────┘                                │
│             ↓ 升级                                          │
│  Level 2: 小型生产环境                                       │
│  ┌─────────────────────────┐                                │
│  │  Docker Compose 编排     │  适用:10-50人团队              │
│  │  API + Model + DB + Cache│                               │
│  └──────────┬──────────────┘                                │
│             ↓ 扩展                                          │
│  Level 3: 中型高可用环境                                      │
│  ┌─────────────────────────┐                                │
│  │  Kubernetes 集群         │  适用:50-200人企业             │
│  │  多副本 + 负载均衡       │                               │
│  └──────────┬──────────────┘                                │
│             ↓ 规模化                                        │
│  Level 4: 企业级生产集群                                     │
│  ┌─────────────────────────┐                                │
│  │  分布式 + 多区域容灾      │  适用:200+人/金融/政府        │
│  └─────────────────────────┘                                │
└─────────────────────────────────────────────────────────────┘

一、Level 1:单机开发环境(快速体验)

1.1 硬件要求

组件 最低配置 推荐配置
CPU 8核 (Intel i7/AMD Ryzen 7) 16核+
内存 32GB DDR4 64GB DDR5
GPU RTX 3090 (24GB VRAM) RTX 4090 / A5000
存储 500GB SSD 1TB NVMe
网络 千兆网卡 万兆网卡

1.2 快速安装脚本

#!/bin/bash
# MonkeyCode 单机一键安装脚本
# 适用于 Ubuntu 22.04 / CentOS 8+

set -e

echo "=== MonkeyCode 单机安装程序 ==="

# 检查系统要求
check_prerequisites() {
    echo "[1/6] 检查系统环境..."
    
    # 检查操作系统
    if [[ -f /etc/os-release ]]; then
        source /etc/os-release
        echo "  操作系统: $PRETTY_NAME"
    fi
    
    # 检查内存(需要至少28GB可用)
    MEM_AVAIL=$(free -g | awk '/Mem:/ {print $7}')
    if [[ $MEM_AVAIL -lt 28 ]]; then
        echo "  ⚠️ 可用内存不足28GB (当前: ${MEM_AVAIL}GB),可能影响性能"
    else
        echo "  ✅ 内存充足: ${MEM_AVAIL}GB 可用"
    fi
    
    # 检查GPU
    if command -v nvidia-smi &> /dev/null; then
        GPU_NAME=$(nvidia-smi --query-gpu=name --format=csv,noheader | head -1)
        GPU_MEM=$(nvidia-smi --query-gpu.memory.total --format=csv,noheader,nounit | head -1)
        echo "  ✅ GPU检测: $GPU_NAME (${GPU_MEM}MB)"
    else
        echo "  ⚠️ 未检测到NVIDIA GPU,将使用CPU模式(速度较慢)"
    fi
    
    # 检查Docker
    if command -v docker &> /dev/null; then
        echo "  ✅ Docker已安装: $(docker --version)"
    else
        install_docker
    fi
}

install_docker() {
    echo "  安装Docker..."
    curl -fsSL https://get.docker.com | sh
    sudo usermod -aG docker $USER
    echo "  ✅ Docker安装完成(请重新登录使组生效)"
}

create_config() {
    echo "[2/6] 生成配置文件..."
    
    SECRET_KEY=$(openssl rand -hex 32)
    DB_PASSWORD=$(openssl rand -base64 16 | tr -d '=/+' | head -c 16; echo)
    REDIS_PASSWORD=$(openssl rand -base64 16 | tr -d '=/+' | head -c 16; echo)
    
    cat > .env << EOF
# MonkeyCode 环境配置 (自动生成于 $(date))
MC_SECRET_KEY=${SECRET_KEY}
DB_USER=monkeycode
DB_PASSWORD=${DB_PASSWORD}
REDIS_PASSWORD=${REDIS_PASSWORD}
MC_MODEL_URL=http://model-service:8081
EOF
    
    chmod 600 .env
    echo "  ✅ 配置文件已生成 (.env)"
}

start_services() {
    echo "[3/6] 拉取镜像并启动服务..."
    
    docker compose pull
    docker compose up -d
    
    echo "[4/6] 等待服务就绪..."
    for i in {1..30}; do
        if curl -s http://localhost:8080/healthz > /dev/null 2>&1; then
            echo "  ✅ 所有服务已就绪!"
            break
        fi
        sleep 3
        echo "  等待中... ($((i*3))秒)"
    done
}

verify_installation() {
    echo "[5/6] 验证安装..."
    
    # 检查各容器状态
    echo ""
    echo "  容器状态:"
    docker compose ps --format "    {{.Name}}: {{.Status}}"
    
    # 测试API
    echo ""
    echo "  API测试:"
    HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:8080/api/v1/health)
    if [[ "$HTTP_CODE" == "200" ]]; then
        echo "  ✅ API健康检查通过 (HTTP $HTTP_CODE)"
    else
        echo "  ⚠️ API返回异常 (HTTP $HTTP_CODE)"
    fi
}

print_summary() {
    echo ""
    echo "========================================="
    echo "  🎉 MonkeyCode 安装完成!"
    echo "========================================="
    echo ""
    echo "  访问地址:"
    echo "    API服务: http://localhost:8080"
    echo "    管理后台: http://localhost:8080/admin"
    echo ""
    echo "  常用命令:"
    echo "    查看日志:   docker compose logs -f"
    echo "    停止服务:   docker compose down"
    echo "    重启服务:   docker compose restart"
    echo ""
    echo "  下一步:"
    echo "    1. 访问管理后台创建管理员账号"
    echo "    2. 安装IDE插件 (VSCode/JetBrains)"
    echo "    3. 开始使用AI编码助手!"
    echo "========================================="
}

# 主流程
main() {
    check_prerequisites
    create_config
    start_services
    verify_installation
    print_summary
}

main

1.3 目录结构说明

monkeycode-deploy/
├── docker-compose.yml      # Docker编排文件
├── .env                    # 环境变量(含密钥)
├── config/
│   ├── monkeycode.yaml     # 主配置文件
│   ├── model-config.yaml   # 模型配置
│   └── security-policy.yaml # 安全策略
├── data/                   # 数据持久化目录
│   ├── postgres/           # 数据库数据
│   ├── redis/              # 缓存数据
│   └── models/             # 模型权重缓存
├── logs/                   # 日志目录
└── scripts/
    ├── install.sh          # 安装脚本
    ├── backup.sh           # 备份脚本
    └── monitor.sh          # 监控脚本

二、Level 2:小型生产环境(Docker Compose)

2.1 推荐硬件配置

团队规模 并发用户数 GPU配置 CPU 内存 存储
10-20人 ~15并发 1× A10G (24GB) 16核 64GB 500GB NVMe
20-50人 ~40并发 2× A10G (48GB) 32核 128GB 1TB NVMe

2.2 完整Docker Compose配置

# docker-compose.prod.yml - 生产环境完整配置
version: '3.8'

services:
  # ========== 前端网关 ==========
  nginx:
    image: nginx:1.25-alpine
    container_name: mc-nginx
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./config/nginx.conf:/etc/nginx/nginx.conf:ro
      - ./ssl:/etc/nginx/ssl:ro
    depends_on:
      - api-server
    restart: always
    deploy:
      resources:
        limits:
          memory: 512M
          cpus: '1'

  # ========== API服务 ==========
  api-server:
    image: monkeycode/monkeycode-server:latest
    container_name: mc-api
    environment:
      MC_DB_HOST: postgres
      MC_DB_PORT: 5432
      MC_DB_NAME: monkeycode
      MC_DB_USER: ${DB_USER}
      MC_DB_PASSWORD: ${DB_PASSWORD}
      MC_REDIS_HOST: redis
      MC_REDIS_PORT: 6379
      MC_REDIS_PASSWORD: ${REDIS_PASSWORD}
      MC_MODEL_URL: http://model-service:8081
      MC_SECRET_KEY: ${MC_SECRET_KEY}
      MC_LOG_LEVEL: info
      MC_MAX_CONCURRENT: 100
    depends_on:
      postgres:
        condition: service_healthy
      redis:
        condition: service_healthy
    restart: always
    deploy:
      resources:
        limits:
          memory: 8G
          cpus: '4'
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:8080/healthz"]
      interval: 30s
      timeout: 10s
      retries: 3

  # ========== AI模型推理服务 ==========
  model-service:
    image: monkeycode/vllm-inference:latest
    container_name: mc-model
    ports:
      - "8081:8081"
    environment:
      MODEL_NAME: monkeycode-7b-int8
      GPU_MEMORY_UTILIZATION: 0.90
      MAX_BATCH_SIZE: 64
      MAX_CONTEXT_LENGTH: 8192
      DTYPE: half
    volumes:
      - model_cache:/models/.cache
    deploy:
      resources:
        reservations:
          devices:
            - driver: nvidia
              count: all
              capabilities: [gpu]
    restart: always
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:8081/health"]
      interval: 60s
      timeout: 15s
      retries: 3

  # ========== PostgreSQL数据库 ==========
  postgres:
    image: postgres:16-alpine
    container_name: mc-postgres
    environment:
      POSTGRES_DB: monkeycode
      POSTGRES_USER: ${DB_USER}
      POSTGRES_PASSWORD: ${DB_PASSWORD}
      PGDATA: /var/lib/postgresql/data/pgdata
    volumes:
      - pg_data:/var/lib/postgresql/data
      - ./init-sql:/docker-entrypoint-initdb.d:ro
    command: >
      postgres
      -c shared_buffers=2GB
      -c effective_cache_size=6GB
      -c maintenance_work_mem=512MB
      -c wal_level=replica
      -c max_wal_senders=3
      -c work_mem=64MB
    restart: always
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U ${DB_USER} -d monkeycode"]
      interval: 10s
      timeout: 5s
      retries: 5

  # ========== Redis缓存 ==========
  redis:
    image: redis:7-alpine
    container_name: mc-redis
    command: >
      redis-server 
      --requirepass ${REDIS_PASSWORD}
      --maxmemory 4gb
      --maxmemory-policy allkeys-lru
      --appendonly yes
      --appendfsync everysec
    volumes:
      - redis_data:/data
    restart: always
    healthcheck:
      test: ["CMD", "redis-cli", "-a", "${REDIS_PASSWORD}", "ping"]
      interval: 10s
      timeout: 5s
      retries: 5

volumes:
  pg_data:
    driver: local
  redis_data:
    driver: local
  model_cache:
    driver: local

networks:
  default:
    name: monkeycode-network
    driver: bridge

2.3 Nginx反向代理配置

# config/nginx.conf - Nginx生产配置
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;

events {
    worker_connections 2048;
    use epoll;
    multi_accept on;
}

http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    # 日志格式
    log_format main '$remote_addr - $remote_user [$time_local] '
                    '"$request" $status $body_bytes_sent '
                    '"$http_referer" "$http_user_agent" '
                    'rt=$request_time';

    access_log /var/log/nginx/access.log main;

    # 性能优化
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;

    # Gzip压缩
    gzip on;
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_types text/plain text/css application/json application/javascript
               text/xml application/xml application/xml+rss text/javascript;
    gzip_min_length 1000;

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

    # 上游定义
    upstream monkeycode_api {
        server api-server:8080 weight=5 max_fails=3 fail_timeout=30s;
        keepalive 32;
    }

    upstream monkeycode_model {
        server model-service:8081 weight=5 max_fails=3 fail_timeout=30s;
        keepalive 16;
    }

    # 主服务器
    server {
        listen 80;
        server_name _;
        
        # 安全头
        add_header X-Frame-Options "SAMEORIGIN" always;
        add_header X-Content-Type-Options "nosniff" always;
        add_header X-XSS-Protection "1; mode=block" always;
        
        # 请求体大小限制(用于大代码文件)
        client_max_body_size 10m;

        # API代理
        location /api/ {
            limit_req zone=api_limit burst=60 nodelay;
            limit_conn conn_limit 20;
            
            proxy_pass http://monkeycode_api;
            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;
            
            # WebSocket支持(实时补全)
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            
            # 超时设置
            proxy_connect_timeout 10s;
            proxy_read_timeout 120s;  # AI推理可能较慢
            proxy_send_timeout 60s;
        }

        # 模型服务代理(仅内网访问)
        location /model/ {
            allow 10.0.0.0/8;
            allow 172.16.0.0/12;
            allow 192.168.0.0/16;
            deny all;
            
            proxy_pass http://monkeycode_model;
            proxy_set_header Host $host;
            proxy_read_timeout 300s;  # 模型加载可能很慢
        }

        # 健康检查端点
        location /healthz {
            access_log off;
            proxy_pass http://monkeycode_api;
        }
        
        # 静态资源缓存
        location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2)$ {
            expires 30d;
            add_header Cache-Control "public, immutable";
        }
    }
}

三、Level 3:中型高可用环境(Kubernetes)

3.1 架构拓扑

┌─────────────────────────────────────────────────────────────┐
│           MonkeyCode K8s 生产集群架构                        │
│                                                             │
│  ┌─────────────┐                                           │
│  │   Ingress   │ (Nginx Ingress Controller)                │
│  │   Gateway   │                                           │
│  └──────┬──────┘                                           │
│         │                                                   │
│  ┌──────┴──────────────────────────┐                       │
│  │         API Server (HPA)        │                       │
│  │  ┌─────┐ ┌─────┐ ┌─────┐      │  replicas: 3-10       │
│  │  │Pod-1│ │Pod-2│ │Pod-3│      │  autoscale by CPU>70% │
│  │  └─────┘ └─────┘ └─────┘      │                       │
│  └──────────────┬─────────────────┘                       │
│                 │                                          │
│  ┌──────────────┴─────────────────┐                        │
│  │      Model Service (GPU Pool)  │                        │
│  │  ┌─────────┐ ┌─────────┐      │  GPU节点专用           │
│  │  │GPU Node1│ │GPU Node2│      │  vLLM推理引擎          │
│  │  │(A10G×2) │ │(A10G×2) │      │                       │
│  │  └─────────┘ └─────────┘      │                       │
│  └────────────────────────────────┘                        │
│                 │                                          │
│  ┌──────────────┴─────────────────┐                        │
│  │     Data Layer (HA)            │                        │
│  │  PostgreSQL(主从)  Redis Cluster│                        │
│  └────────────────────────────────┘                        │
│                                                             │
│  监控: Prometheus + Grafana                                 │
│  日志: ELK Stack                                           │
│  追踪: Jaeger                                              │
└─────────────────────────────────────────────────────────────┘

3.2 Kubernetes核心资源清单

# k8s/api-deployment.yaml - API服务部署
apiVersion: apps/v1
kind: Deployment
metadata:
  name: monkeycode-api
  namespace: monkeycode
  labels:
    app: monkeycode-api
spec:
  replicas: 3
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 0
  selector:
    matchLabels:
      app: monkeycode-api
  template:
    metadata:
      labels:
        app: monkeycode-api
      annotations:
        prometheus.io/scrape: "true"
        prometheus.io/port: "8080"
        prometheus.io/path: "/metrics"
    spec:
      affinity:
        podAntiAffinity:
          preferredDuringSchedulingIgnoredDuringExecution:
            - weight: 100
              podAffinityTerm:
                labelSelector:
                  matchLabels:
                    app: monkeycode-api
                topologyKey: kubernetes.io/hostname
      containers:
        - name: api
          image: monkeycode/monkeycode-server:v3.2.0
          ports:
            - containerPort: 8080
              name: http
            - containerPort: 9090
              name: metrics
          envFrom:
            - secretRef:
                name: monkeycode-secrets
            - configMapRef:
                name: monkeycode-config
          resources:
            requests:
              cpu: "2"
              memory: "4Gi"
            limits:
              cpu: "4"
              memory: "8Gi"
          livenessProbe:
            httpGet:
              path: /healthz
              port: 8080
            initialDelaySeconds: 30
            periodSeconds: 10
          readinessProbe:
            httpGet:
              path: /ready
              port: 8080
            initialDelaySeconds: 5
            periodSeconds: 5
          volumeMounts:
            - name: config-volume
              mountPath: /app/config
              readOnly: true
      volumes:
        - name: config-volume
          configMap:
            name: monkeycode-config
---
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: monkeycode-api-hpa
  namespace: monkeycode
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: monkeycode-api
  minReplicas: 3
  maxReplicas: 10
  metrics:
    - type: Resource
      resource:
        name: cpu
        target:
          type: Utilization
          averageUtilization: 70
    - type: Resource
      resource:
        name: memory
        target:
          type: Utilization
          averageUtilization: 80
  behavior:
    scaleDown:
      stabilizationWindowSeconds: 300
      policies:
        - type: Percent
          value: 10
          periodSeconds: 60
    scaleUp:
      stabilizationWindowSeconds: 60
      policies:
        - type: Percent
          value: 100
          periodSeconds: 15

3.3 GPU模型服务部署

# k8s/model-service.yaml - GPU推理服务
apiVersion: apps/v1
kind: Deployment
metadata:
  name: monkeycode-model
  namespace: monkeycode
spec:
  replicas: 2
  selector:
    matchLabels:
      app: monkeycode-model
  template:
    metadata:
      labels:
        app: monkeycode-model
    spec:
      nodeSelector:
        gpu-node: "true"  # 仅调度到GPU节点
      tolerations:
        - key: "nvidia.com/gpu"
          operator: "Exists"
          effect: "NoSchedule"
      containers:
        - name: model
          image: monkeycode/vllm-inference:v3.2.0
          ports:
            - containerPort: 8081
              name: inference
          env:
            - name: MODEL_NAME
              value: "monkeycode-7b-int8"
            - name: GPU_MEMORY_UTILIZATION
              value: "0.92"
            - name: MAX_BATCH_SIZE
              value: "128"
            - name: MAX_NUM_SEQS
              value: "256"
            - name: DTYPE
              value: "half"
          resources:
            limits:
              nvidia.com/gpu: 1
            requests:
              cpu: "4"
              memory: "16Gi"
          volumeMounts:
            - name: model-cache
              mountPath: /models/.cache
      volumes:
        - name: model-cache
          persistentVolumeClaim:
            claimName: model-cache-pvc
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: model-cache-pvc
  namespace: monkeycode
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 200Gi
  storageClassName: premium-ssd  # 高性能SSD

3.4 高可用数据库配置

# k8s/postgres-ha.yaml - PostgreSQL主从高可用
apiVersion: postgresql.cnpg.io/v1
kind: Cluster
metadata:
  name: monkeycode-db
  namespace: monkeycode
spec:
  instances: 3  # 1主2从
  
  # 主实例配置
  primaryUpdateStrategy: unsupervised
  
  # PostgreSQL配置
  postgresql:
    parameters:
      max_connections: "300"
      shared_buffers: "2GB"
      effective_cache_size: "6GB"
      maintenance_work_mem: "512MB"
      work_mem: "64MB"
      random_page_cost: "1.1"  # 优化SSD
      
  # 资源配置
  resources:
    requests:
      cpu: "2"
      memory: "8Gi"
    limits:
      cpu: "4"
      memory: "16Gi"
      
  # 存储配置
  storage:
    size: 200Gi
    storageClass: premium-ssd
    
  # 备份配置
  backup:
    barmanObjectStore:
      destinationPath: "s3://monkeycode-backups/postgres/"
      s3Credentials:
        accessKeyId:
          name: aws-creds
          key: accessKeyId
        secretAccessKey:
          name: aws-creds
          key: secretAccessKey
        region:
          name: aws-creds
          key: region
    retentionPolicy: "30d"
    schedule: "0 2 * * *"  # 每天凌晨2点备份

四、Level 4:企业级多区域容灾架构

4.1 多活架构设计

                         ┌─────────────────┐
                         │   Global LB     │
                         │  (CloudFlare/   │
                         │   AWS Route53)  │
                         └────────┬────────┘
                                  │
            ┌─────────────────────┼─────────────────────┐
            ▼                     ▼                     ▼
   ┌────────────────┐   ┌────────────────┐   ┌────────────────┐
   │  Region: 北京   │   │  Region: 上海   │   │  Region: 深圳   │
   │                │   │                │   │                │
   │ ┌────────────┐ │   │ ┌────────────┐ │   │ ┌────────────┐ │
   │ │ K8s Cluster │ │   │ │ K8s Cluster │ │   │ │ K8s Cluster │ │
   │ │ (Primary)  │◄┼──►││ (Secondary) │◄┼──►││ (DR)       │ │
   │ └────────────┘ │   │ └────────────┘ │   │ └────────────┘ │
   │                │   │                │   │                │
   │ PostgreSQL主  │←─→│ PostgreSQL从  │←─→│ PostgreSQL异步 │
   │ Redis Cluster │←─→│ Redis Replica │   │ (冷备)        │
   └────────────────┘   └────────────────┘   └────────────────┘
            │                     │                     │
            └─────────────────────┼─────────────────────┘
                                  ▼
                    ┌─────────────────────────┐
                    │   S3/OSS 对象存储       │
                    │   (模型权重/备份/日志)  │
                    └─────────────────────────┘

4.2 关键配置要点

维度 配置策略 实现方式
流量调度 就近接入 + 故障切换 DNS智能解析 + 全局LB健康检查
数据同步 异步复制 + 冲突解决 PostgreSQL逻辑复制 + CRDT
会话保持 区域亲和 + 跨区迁移 Sticky Session + JWT无状态
故障恢复 RTO < 5min, RPO < 1min 自动Failover + 同步热备
容量规划 弹性伸缩 + 预留缓冲 HPA + VPA + Cluster Autoscaler

五、运维监控体系

5.1 核心监控指标

# MonkeyCode 关键监控指标定义
MONKEYCODE_METRICS = {
    # API层指标
    "api": {
        "mc_http_requests_total": "API请求总数(按endpoint/status/method维度)",
        "mc_http_request_duration_seconds": "API响应延迟分布",
        "mc_active_connections": "当前活跃连接数",
        "mc_completion_tokens_total": "生成的token总数",
        "mc_completion_acceptance_rate": "补全接受率",
    },
    
    # 模型服务指标
    "model": {
        "mc_inference_latency_p50": "推理延迟P50",
        "mc_inference_latency_p99": "推理延迟P99",
        "mc_gpu_utilization": "GPU利用率",
        "mc_gpu_memory_used_bytes": "GPU显存使用量",
        "mc_batch_size_current": "当前批处理大小",
        "mc_queue_length": "请求队列长度",
    },
    
    # 业务指标
    "business": {
        "mc_daily_active_users": "日活跃用户数",
        "mc_completions_per_user_session": "人均每会话补全次数",
        "mc_error_rate": "错误率(按类型分类)",
        "mc_satisfaction_score": "用户满意度评分",
    },
    
    # 告警规则示例
    "alerts": [
        {"name": "HighLatency", "condition": "p99 > 2s", "severity": "warning"},
        {"name": "HighErrorRate", "condition": "error_rate > 5%", "severity": "critical"},
        {"name": "GPUOverloaded", "condition": "gpu_util > 95% for 5min", "severity": "warning"},
        {"name": "QueueBacklog", "condition": "queue_length > 100", "severity": "critical"},
    ]
}

5.2 运维自动化脚本

#!/bin/bash
# MonkeyCode 运维工具箱

case "$1" in
    status)
        echo "=== MonkeyCode 服务状态 ==="
        docker compose ps
        echo ""
        echo "=== 资源使用 ==="
        docker stats --no-stream --format "table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}\t{{.NetIO}}"
        ;;
    
    logs)
        echo "=== 最近100行日志 ==="
        docker compose logs --tail=100 -f "${2:-api-server}"
        ;;
    
    backup)
        echo "=== 执行数据库备份 ==="
        BACKUP_DIR="./backups/$(date +%Y%m%d_%H%M%S)"
        mkdir -p "$BACKUP_DIR"
        docker exec mc-postgres pg_dump -U monkeycode monkeycode | gzip > "$BACKUP_DIR/db.sql.gz"
        echo "✅ 备份完成: $BACKUP_DIR/db.sql.gz"
        ;;
    
    update)
        echo "=== 更新MonkeyCode版本 ==="
        docker compose pull
        docker compose up -d --force-recreate
        echo "✅ 更新完成"
        ;;
    
    scale)
        if [ -z "$2" ]; then
            echo "用法: $0 scale <数量>"
            exit 1
        fi
        echo "=== 扩展API实例至 $2 个 ==="
        docker compose up -d --scale api-server=$2
        ;;
    
    *)
        echo "MonkeyCode 运维工具箱"
        echo ""
        echo "用法: $0 {status|logs|backup|update|scale}"
        echo ""
        echo "命令:"
        echo "  status          查看服务状态和资源使用"
        echo "  logs [服务名]    查看日志"
        echo "  backup          备份数据库"
        echo "  update          更新到最新版本"
        echo "  scale <数量>    扩展API实例数"
        ;;
esac

六、部署选型决策树

你的团队情况?
│
├─ <10人 / POC验证
│  └→ Level 1: 单机Docker Compose
│     成本: ~5万(一次性硬件)
│     时间: 半天内部署完成
│
├─ 10-50人 / 正式使用
│  └→ Level 2: Docker Compose + Nginx
│     成本: ~10-20万
│     时间: 1-2天部署完成
│
├─ 50-200人 / 核心业务依赖
│  └→ Level 3: Kubernetes集群
│     成本: ~30-80万/年
│     时间: 1-2周部署+调优
│
├─ 200+人 / 金融/政府/高合规
│  └→ Level 4: 多区域容灾集群
│     成本: ~100万+/年
│     时间: 1个月规划实施
│
└─ 不确定?
   └→ 先用Level 1试用2周,再根据实际需求升级

总结

MonkeyCode的部署架构设计遵循一个核心理念:从小起步,按需扩展。

  • 🚀 快速验证:单机Docker Compose,半天内跑起来
  • 📈 弹性增长:水平扩展API,垂直扩展GPU
  • 🛡️ 高可用保障:K8s自动故障转移,多区域容灾
  • 💰 成本可控:开源免费软件 + 自主选择硬件规格

💡 建议:大多数企业可以从Level 2开始,根据实际使用情况和团队规模逐步升级。不要一开始就过度设计——MonkeyCode的架构支持平滑演进。


下一篇预告:《MonkeyCode开源许可证解读:Apache 2.0如何保障企业自由使用》

posted on 2026-06-22 10:50  MonkeyCode  阅读(32)  评论(0)    收藏  举报