腾讯云完整部署方案:CODING + CI/CD + Docker + Nginx + K8s 扩展

完整部署方案:CODING + CI/CD + Docker + Nginx + K8s 扩展

📋 方案概览

BASH

markdown 复制代码
代码开发 → CODING 仓库 → CI/CD 流水线 → 构建镜像 → 部署到服务器 → Nginx 反向代理 → 监控运维
    │           │              │              │              │              │
    ▼           ▼              ▼              ▼              ▼              ▼
  本地开发   Git 推送    自动测试构建   Docker 镜像    容器编排      域名访问
  环境搭建   代码管理    质量门禁      版本管理       服务发现      负载均衡

第一阶段:开发环境准备

1.1 项目结构规划

BASH

csharp 复制代码
project-root/
├── frontend/                 # Next.js 前端项目
│   ├── src/
│   ├── public/
│   ├── Dockerfile           # 前端容器配置
│   ├── nginx.conf           # 前端 Nginx 配置(生产环境)
│   └── package.json
├── backend/                  # FastAPI 后端项目
│   ├── app/
│   ├── requirements.txt
│   ├── Dockerfile           # 后端容器配置
│   └── main.py
├── docker-compose.yml        # 本地开发编排
├── nginx/
│   └── nginx.conf           # 生产环境 Nginx 配置
└── .coding-ci.yml           # CODING 流水线配置

1.2 前端 Dockerfile(frontend/Dockerfile)

DOCKERFILE

bash 复制代码
# 构建阶段
FROM node:18-alpine AS builder

WORKDIR /app

# 配置 npm 镜像源
RUN npm config set registry https://registry.npmmirror.com/

# 安装依赖
COPY package*.json ./
RUN npm ci

# 复制源码并构建
COPY . .
RUN npm run build

# 生产阶段
FROM node:18-alpine AS runner

WORKDIR /app

ENV NODE_ENV=production

# 复制构建产物
COPY --from=builder /app/public ./public
COPY --from=builder /app/.next/standalone ./
COPY --from=builder /app/.next/static ./.next/static

EXPOSE 3000

CMD ["node", "server.js"]

⚠️ 注意事项

  • Next.js 需要配置 output: 'standalone' 才能独立运行
  • 多阶段构建减少镜像体积(从 1GB+ 降到 200MB)

1.3 后端 Dockerfile(backend/Dockerfile)

DOCKERFILE

bash 复制代码
FROM python:3.11-slim

WORKDIR /app

# 配置 pip 镜像源
RUN pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple

# 安装依赖
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# 复制应用代码
COPY . .

EXPOSE 8080

CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8080"]

1.4 本地 docker-compose.yml

YAML

yaml 复制代码
version: '3.8'

services:
  frontend:
    build: ./frontend
    ports:
      - "3000:3000"
    environment:
      - NEXT_PUBLIC_API_URL=http://localhost:8080
    networks:
      - app-network

  backend:
    build: ./backend
    ports:
      - "8080:8080"
    environment:
      - DATABASE_URL=postgresql://user:pass@db:5432/app
    networks:
      - app-network

  db:
    image: postgres:15-alpine
    environment:
      - POSTGRES_USER=user
      - POSTGRES_PASSWORD=pass
      - POSTGRES_DB=app
    volumes:
      - postgres_data:/var/lib/postgresql/data
    networks:
      - app-network

networks:
  app-network:
    driver: bridge

volumes:
  postgres_data:

第二阶段:CODING 平台配置

2.1 创建 CODING 项目

  1. 登录 CODING
  2. 创建项目 → 选择「DevOps 项目」
  3. 填写项目名称:my-fullstack-app
  4. 开启功能:代码仓库、持续集成、制品仓库

2.2 代码仓库初始化

BASH

csharp 复制代码
# 本地项目关联 CODING 仓库
git init
git add .
git commit -m "Initial commit"

# 添加 CODING 远程仓库(替换为实际地址)
git remote add origin https://e.coding.net/your-team/my-fullstack-app/frontend.git

# 推送代码
git push -u origin main

⚠️ 注意事项

  • 前后端可以放在同一个项目的不同仓库,或不同项目
  • 建议:同一项目多仓库,便于统一管理

2.3 配置 SSH 密钥(用于流水线部署)

在服务器上生成密钥

BASH

perl 复制代码
# 登录服务器
ssh root@81.70.31.114

# 生成密钥(不要设置密码)
ssh-keygen -t rsa -b 4096 -C "deploy@coding" -f ~/.ssh/coding_deploy

# 查看公钥
cat ~/.ssh/coding_deploy.pub
# 输出:ssh-rsa AAAAB3... deploy@coding

在 CODING 配置私钥

  1. 项目设置 → 开发者选项 → 凭据管理
  2. 新建凭据 → SSH 私钥
  3. 名称:production-server-key
  4. 内容:复制服务器上的 ~/.ssh/coding_deploy 私钥内容

在服务器配置授权

BASH

bash 复制代码
# 将公钥添加到 authorized_keys
cat ~/.ssh/coding_deploy.pub >> ~/.ssh/authorized_keys

# 设置权限
chmod 600 ~/.ssh/authorized_keys
chmod 700 ~/.ssh

# 测试连接(在 CODING 流水线中测试)

第三阶段:CI/CD 流水线配置

3.1 完整流水线配置(.coding-ci.yml)

YAML

bash 复制代码
# 定义阶段
stages:
  - build
  - test
  - package
  - deploy

# 变量定义
variables:
  DOCKER_REGISTRY: your-team-docker.pkg.coding.net
  FRONTEND_IMAGE: $DOCKER_REGISTRY/my-fullstack-app/frontend
  BACKEND_IMAGE: $DOCKER_REGISTRY/my-fullstack-app/backend
  SERVER_IP: 81.70.31.114
  DEPLOY_PATH: /opt/app

# 构建前端
build-frontend:
  stage: build
  image: node:18-alpine
  script:
    - cd frontend
    - npm config set registry https://registry.npmmirror.com/
    - npm ci
    - npm run build
  artifacts:
    paths:
      - frontend/.next/
    expire_in: 1 hour
  cache:
    key: frontend-node-modules
    paths:
      - frontend/node_modules/

# 构建后端
build-backend:
  stage: build
  image: python:3.11-slim
  script:
    - cd backend
    - pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
    - pip install -r requirements.txt
  cache:
    key: backend-pip
    paths:
      - /root/.cache/pip/

# 测试阶段
test-frontend:
  stage: test
  image: node:18-alpine
  script:
    - cd frontend
    - npm ci
    - npm run test:ci
  allow_failure: false

test-backend:
  stage: test
  image: python:3.11-slim
  script:
    - cd backend
    - pip install -r requirements.txt
    - pip install pytest
    - pytest tests/ -v
  allow_failure: false

# 打包镜像
package-frontend:
  stage: package
  image: docker:24
  services:
    - docker:24-dind
  script:
    - docker login -u $CODING_ARTIFACTS_USER -p $CODING_ARTIFACTS_PASSWORD $DOCKER_REGISTRY
    - cd frontend
    - docker build -t $FRONTEND_IMAGE:$CI_COMMIT_SHA -t $FRONTEND_IMAGE:latest .
    - docker push $FRONTEND_IMAGE:$CI_COMMIT_SHA
    - docker push $FRONTEND_IMAGE:latest
  only:
    - main

package-backend:
  stage: package
  image: docker:24
  services:
    - docker:24-dind
  script:
    - docker login -u $CODING_ARTIFACTS_USER -p $CODING_ARTIFACTS_PASSWORD $DOCKER_REGISTRY
    - cd backend
    - docker build -t $BACKEND_IMAGE:$CI_COMMIT_SHA -t $BACKEND_IMAGE:latest .
    - docker push $BACKEND_IMAGE:$CI_COMMIT_SHA
    - docker push $BACKEND_IMAGE:latest
  only:
    - main

# 部署到生产环境
deploy-production:
  stage: deploy
  image: alpine/ssh:latest
  before_script:
    - apk add --no-cache openssh-client
    - eval $(ssh-agent -s)
    - echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add -
    - mkdir -p ~/.ssh
    - chmod 700 ~/.ssh
    - ssh-keyscan -H $SERVER_IP >> ~/.ssh/known_hosts
  script:
    # 复制部署脚本到服务器
    - scp -r docker-compose.prod.yml nginx/ root@$SERVER_IP:$DEPLOY_PATH/
    
    # 执行远程部署
    - |
      ssh root@$SERVER_IP << 'EOF'
        cd /opt/app
        
        # 登录镜像仓库
        docker login -u $CODING_ARTIFACTS_USER -p $CODING_ARTIFACTS_PASSWORD $DOCKER_REGISTRY
        
        # 拉取最新镜像
        docker pull $FRONTEND_IMAGE:latest
        docker pull $BACKEND_IMAGE:latest
        
        # 优雅重启(使用 docker-compose)
        docker-compose -f docker-compose.prod.yml down
        docker-compose -f docker-compose.prod.yml up -d
        
        # 清理旧镜像
        docker image prune -f
        
        # 健康检查
        sleep 10
        curl -f http://localhost:80/health || exit 1
        echo "部署成功!"
      EOF
  only:
    - main
  environment:
    name: production
    url: http://81.70.31.114

3.2 生产环境编排(docker-compose.prod.yml)

YAML

yaml 复制代码
version: '3.8'

services:
  nginx:
    image: nginx:alpine
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./nginx/nginx.conf:/etc/nginx/conf.d/default.conf:ro
      - ./nginx/ssl:/etc/nginx/ssl:ro
    depends_on:
      - frontend
      - backend
    networks:
      - app-network
    restart: always

  frontend:
    image: ${DOCKER_REGISTRY}/my-fullstack-app/frontend:latest
    expose:
      - "3000"
    environment:
      - NODE_ENV=production
      - NEXT_PUBLIC_API_URL=/api
    networks:
      - app-network
    restart: always
    deploy:
      replicas: 2  # 运行 2 个实例

  backend:
    image: ${DOCKER_REGISTRY}/my-fullstack-app/backend:latest
    expose:
      - "8080"
    environment:
      - DATABASE_URL=postgresql://user:pass@db:5432/app
      - REDIS_URL=redis://redis:6379
    depends_on:
      - db
      - redis
    networks:
      - app-network
    restart: always
    deploy:
      replicas: 2

  db:
    image: postgres:15-alpine
    environment:
      - POSTGRES_USER=user
      - POSTGRES_PASSWORD=${DB_PASSWORD}
      - POSTGRES_DB=app
    volumes:
      - postgres_data:/var/lib/postgresql/data
    networks:
      - app-network
    restart: always

  redis:
    image: redis:7-alpine
    networks:
      - app-network
    restart: always

networks:
  app-network:
    driver: bridge

volumes:
  postgres_data:

第四阶段:Nginx 配置详解

4.1 完整 Nginx 配置(nginx/nginx.conf)

NGINX

ini 复制代码
# 上游服务配置
upstream frontend {
    server frontend:3000;
    # 多实例负载均衡
    # server frontend:3000 weight=5;
}

upstream backend {
    server backend:8080;
    # server backend2:8080;
}

# 主域名配置
server {
    listen 80;
    server_name web.app.com;
    
    # 日志配置
    access_log /var/log/nginx/web.app.com.access.log;
    error_log /var/log/nginx/web.app.com.error.log;
    
    # 安全响应头
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;
    
    # 禁止访问广场页面
    location /square {
        return 404;
    }
    
    # API 代理
    location /api/ {
        proxy_pass http://backend/;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        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;
        proxy_cache_bypass $http_upgrade;
        
        # 超时设置
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
    }
    
    # 前端页面
    location / {
        proxy_pass http://frontend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
    
    # Next.js 静态资源缓存(关键优化)
    location /_next/static/ {
        proxy_pass http://frontend;
        expires 1y;
        add_header Cache-Control "public, immutable";
        access_log off;
    }
    
    # 图片等静态资源
    location ~* .(jpg|jpeg|png|gif|ico|svg|woff|woff2|ttf|eot)$ {
        proxy_pass http://frontend;
        expires 6M;
        add_header Cache-Control "public";
        access_log off;
    }
    
    # 健康检查
    location /health {
        access_log off;
        return 200 "healthy\n";
        add_header Content-Type text/plain;
    }
}

# 广场专用域名
server {
    listen 80;
    server_name www.app.com;
    
    access_log /var/log/nginx/www.app.com.access.log;
    error_log /var/log/nginx/www.app.com.error.log;
    
    # 根路径重写到广场
    location / {
        proxy_pass http://frontend/square;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
    
    # 静态资源
    location /_next/ {
        proxy_pass http://frontend;
        expires 1y;
        add_header Cache-Control "public, immutable";
    }
    
    # 禁止访问其他页面
    location ~ ^/(?!square|_next|api) {
        return 404;
    }
}

# 后端 API 独立域名(可选)
server {
    listen 80;
    server_name api.app.com;
    
    location / {
        proxy_pass http://backend;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

第五阶段:服务器部署操作

5.1 首次部署步骤

BASH

bash 复制代码
# 1. 登录服务器
ssh root@81.70.31.114

# 2. 创建应用目录
mkdir -p /opt/app
cd /opt/app

# 3. 配置 Docker 镜像加速
mkdir -p /etc/docker
cat > /etc/docker/daemon.json << 'EOF'
{
  "registry-mirrors": [
    "https://mirror.ccs.tencentyun.com",
    "https://hub-mirror.c.163.com"
  ],
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "10m",
    "max-file": "3"
  }
}
EOF
systemctl daemon-reload
systemctl restart docker

# 4. 安装 docker-compose
curl -L "https://github.com/docker/compose/releases/download/v2.23.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
chmod +x /usr/local/bin/docker-compose

# 5. 创建必要文件
touch docker-compose.prod.yml
mkdir -p nginx/ssl

# 6. 开放防火墙端口(只开放 80/443)
# 在腾讯云控制台操作,或执行:
ufw allow 80/tcp
ufw allow 443/tcp
ufw enable

5.2 容器管理命令速查

操作 命令
查看运行容器 ```docker ps`
查看所有容器 ```docker ps -a`
查看容器日志 ```docker logs -f <容器名>`
进入容器 ```docker exec -it <容器名> sh`
重启容器 ```docker restart <容器名>`
停止容器 ```docker stop <容器名>`
删除容器 ```docker rm <容器名>`
查看资源使用 ```docker stats`
清理无用镜像 ```docker image prune -f`
查看网络 ```docker network ls`
查看卷 ```docker volume ls`

5.3 常用运维脚本

一键部署脚本deploy.sh):

BASH

bash 复制代码
#!/bin/bash
set -e

echo "🚀 开始部署..."

# 拉取最新代码
cd /opt/app
git pull origin main

# 登录镜像仓库
docker login -u $CODING_USER -p $CODING_PASS your-team-docker.pkg.coding.net

# 拉取最新镜像
docker-compose -f docker-compose.prod.yml pull

# 优雅重启
docker-compose -f docker-compose.prod.yml up -d --remove-orphans

# 清理
docker image prune -f

# 健康检查
sleep 5
if curl -f http://localhost/health > /dev/null 2>&1; then
    echo "✅ 部署成功!"
else
    echo "❌ 健康检查失败"
    exit 1
fi

日志查看脚本logs.sh):

BASH

bash 复制代码
#!/bin/bash

SERVICE=${1:-all}

if [ "$SERVICE" = "all" ]; then
    docker-compose -f /opt/app/docker-compose.prod.yml logs -f
else
    docker logs -f $SERVICE
fi

第六阶段:监控与日志

6.1 安装 Prometheus + Grafana(可选)

YAML

yaml 复制代码
# docker-compose.monitoring.yml
version: '3.8'

services:
  prometheus:
    image: prom/prometheus:latest
    ports:
      - "9090:9090"
    volumes:
      - ./prometheus.yml:/etc/prometheus/prometheus.yml
      - prometheus_data:/prometheus
    networks:
      - app-network

  grafana:
    image: grafana/grafana:latest
    ports:
      - "3001:3000"
    volumes:
      - grafana_data:/var/lib/grafana
    networks:
      - app-network

  node-exporter:
    image: prom/node-exporter:latest
    ports:
      - "9100:9100"
    networks:
      - app-network

volumes:
  prometheus_data:
  grafana_data:

networks:
  app-network:
    external: true

6.2 应用性能监控(APM)

前端:集成 Sentry

JAVASCRIPT

php 复制代码
// frontend/sentry.client.config.js
import * as Sentry from '@sentry/nextjs';

Sentry.init({
  dsn: 'your-sentry-dsn',
  tracesSampleRate: 1.0,
});

后端:集成 Prometheus 客户端

PYTHON

python 复制代码
# backend/main.py
from prometheus_client import Counter, Histogram, generate_latest

REQUEST_COUNT = Counter('http_requests_total', 'Total requests')
REQUEST_LATENCY = Histogram('http_request_duration_seconds', 'Request latency')

@app.get("/metrics")
def metrics():
    return generate_latest()

第七阶段:Kubernetes 扩展(进阶)

7.1 何时需要 K8s?

场景 Docker Compose Kubernetes
单台服务器 ✅ 足够 ❌ 过度设计
多台服务器 ❌ 手动管理 ✅ 自动调度
自动扩缩容 ❌ 不支持 ✅ HPA
服务发现 ❌ 手动配置 ✅ 内置 DNS
滚动更新 ⚠️ 需脚本 ✅ 原生支持
自愈能力 ❌ 无 ✅ 自动重启

7.2 K8s 部署配置

Namespace 配置

YAML

vbnet 复制代码
# k8s/namespace.yaml
apiVersion: v1
kind: Namespace
metadata:
  name: production

前端 Deployment

YAML

yaml 复制代码
# k8s/frontend-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: frontend
  namespace: production
spec:
  replicas: 3
  selector:
    matchLabels:
      app: frontend
  template:
    metadata:
      labels:
        app: frontend
    spec:
      containers:
      - name: frontend
        image: your-registry/frontend:latest
        ports:
        - containerPort: 3000
        resources:
          requests:
            memory: "256Mi"
            cpu: "250m"
          limits:
            memory: "512Mi"
            cpu: "500m"
        livenessProbe:
          httpGet:
            path: /health
            port: 3000
          initialDelaySeconds: 30
          periodSeconds: 10
        readinessProbe:
          httpGet:
            path: /health
            port: 3000
          initialDelaySeconds: 5
          periodSeconds: 5
---
apiVersion: v1
kind: Service
metadata:
  name: frontend
  namespace: production
spec:
  selector:
    app: frontend
  ports:
  - port: 80
    targetPort: 3000
  type: ClusterIP

后端 Deployment

YAML

yaml 复制代码
# k8s/backend-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: backend
  namespace: production
spec:
  replicas: 3
  selector:
    matchLabels:
      app: backend
  template:
    metadata:
      labels:
        app: backend
    spec:
      containers:
      - name: backend
        image: your-registry/backend:latest
        ports:
        - containerPort: 8080
        env:
        - name: DATABASE_URL
          valueFrom:
            secretKeyRef:
              name: app-secrets
              key: database-url
        resources:
          requests:
            memory: "512Mi"
            cpu: "500m"
          limits:
            memory: "1Gi"
            cpu: "1000m"
---
apiVersion: v1
kind: Service
metadata:
  name: backend
  namespace: production
spec:
  selector:
    app: backend
  ports:
  - port: 80
    targetPort: 8080
  type: ClusterIP

Ingress 配置(替代 Nginx)

YAML

yaml 复制代码
# k8s/ingress.yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: app-ingress
  namespace: production
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /
    cert-manager.io/cluster-issuer: "letsencrypt"
spec:
  ingressClassName: nginx
  tls:
  - hosts:
    - web.app.com
    - www.app.com
    secretName: app-tls
  rules:
  - host: web.app.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: frontend
            port:
              number: 80
      - path: /api
        pathType: Prefix
        backend:
          service:
            name: backend
            port:
              number: 80
  - host: www.app.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: frontend
            port:
              number: 80

HPA 自动扩缩容

YAML

yaml 复制代码
# k8s/hpa.yaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: frontend-hpa
  namespace: production
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: frontend
  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

7.3 K8s 部署命令

BASH

bash 复制代码
# 应用所有配置
kubectl apply -f k8s/namespace.yaml
kubectl apply -f k8s/frontend-deployment.yaml
kubectl apply -f k8s/backend-deployment.yaml
kubectl apply -f k8s/ingress.yaml
kubectl apply -f k8s/hpa.yaml

# 查看状态
kubectl get pods -n production
kubectl get svc -n production
kubectl get ingress -n production
kubectl get hpa -n production

# 查看日志
kubectl logs -f deployment/frontend -n production

# 进入容器
kubectl exec -it deployment/frontend -n production -- sh

# 扩缩容
kubectl scale deployment frontend --replicas=5 -n production

第八阶段:完整流程图

BASH

sql 复制代码
┌─────────────────────────────────────────────────────────────────────────┐
│                           开发阶段                                       │
│  ┌─────────────┐    ┌─────────────┐    ┌─────────────┐                 │
│  │ 本地开发     │───▶│ 编写 Dockerfile│───▶│ 本地测试     │                 │
│  │ npm run dev │    │ docker build │    │ docker-compose│                │
│  └─────────────┘    └─────────────┘    └─────────────┘                 │
└─────────────────────────────────────────────────────────────────────────┘
                                    │
                                    ▼
┌─────────────────────────────────────────────────────────────────────────┐
│                           代码管理                                       │
│  ┌─────────────┐    ┌─────────────┐    ┌─────────────┐                 │
│  │ git add     │───▶│ git commit  │───▶│ git push    │                 │
│  └─────────────┘    └─────────────┘    └──────┬──────┘                 │
│                                               │                         │
│                                               ▼                         │
│                                        ┌─────────────┐                 │
│                                        │ CODING 仓库  │                 │
│                                        │ 触发 Webhook │                 │
│                                        └──────┬──────┘                 │
└─────────────────────────────────────────────────────────────────────────┘
                                                │
                                                ▼
┌─────────────────────────────────────────────────────────────────────────┐
│                           CI/CD 流水线                                   │
│  ┌─────────┐   ┌─────────┐   ┌─────────┐   ┌─────────┐   ┌─────────┐   │
│  │ 代码检出 │──▶│ 依赖安装 │──▶│ 运行测试 │──▶│ 构建镜像 │──▶│ 推送仓库 │   │
│  │ Checkout│   │ Install │   │  Test   │   │  Build  │   │  Push   │   │
│  └─────────┘   └─────────┘   └─────────┘   └─────────┘   └────┬────┘   │
│                                                               │         │
└───────────────────────────────────────────────────────────────┼─────────┘
                                                                │
                                                                ▼
┌─────────────────────────────────────────────────────────────────────────┐
│                           部署阶段                                       │
│  ┌─────────────┐    ┌─────────────┐    ┌─────────────┐                 │
│  │ SSH 连接    │───▶│ 拉取镜像    │───▶│ 启动容器    │                 │
│  │ 服务器      │    │ docker pull │    │ compose up  │                 │
│  └─────────────┘    └─────────────┘    └──────┬──────┘                 │
│                                               │                         │
│                                               ▼                         │
│  ┌─────────────────────────────────────────────────────────────────┐   │
│  │                     容器运行时                                    │   │
│  │  ┌─────────┐      ┌─────────┐      ┌─────────┐      ┌────────┐ │   │
│  │  │  Nginx  │◄────▶│ Frontend│      │ Backend │◄────▶│   DB   │ │   │
│  │  │  :80    │      │  :3000  │      │  :8080  │      │ 5432   │ │   │
│  │  │ 入口网关 │      │ Next.js │      │ FastAPI │      │PostgreSQL│  │
│  │  └────┬────┘      └─────────┘      └─────────┘      └────────┘ │   │
│  │       │                                                        │   │
│  │       └───────────────────────────────────────────────────────▶│   │
│  │                          用户访问                               │   │
│  └─────────────────────────────────────────────────────────────────┘   │
└─────────────────────────────────────────────────────────────────────────┘
                                    │
                                    ▼
┌─────────────────────────────────────────────────────────────────────────┐
│                           运维监控                                       │
│  ┌─────────┐    ┌─────────┐    ┌─────────┐    ┌─────────┐              │
│  │ 日志收集 │    │ 性能监控 │    │ 告警通知 │    │ 自动扩缩 │              │
│  │  ELK   │    │Prometheus│    │ 钉钉/微信│    │   HPA   │              │
│  └─────────┘    └─────────┘    └─────────┘    └─────────┘              │
└─────────────────────────────────────────────────────────────────────────┘

关键注意事项总结

阶段 注意事项
****开发 本地使用 Docker Compose 保持环境一致
****Git 大文件使用 Git LFS,敏感信息放 .env
****CI/CD 并行构建加速,缓存 node_modules
****镜像 使用多阶段构建,配置国内镜像源
****部署 蓝绿部署或滚动更新,避免服务中断
****Nginx 配置静态缓存,开启 Gzip 压缩
****安全 不暴露非必要端口,使用非 root 用户运行容器
****监控 健康检查端点,日志集中收集
****K8s 资源限制必须设置,避免节点资源耗尽

这份方案涵盖了从开发到生产的完整流程。建议您按阶段实施,先跑通 Docker Compose 版本,再逐步添加 CI/CD 和监控。需要我针对某个具体阶段详细展开吗?

相关推荐
比奇堡鱼贩2 小时前
python第五次作业
开发语言·前端·python
半兽先生3 小时前
使用 retire.js 自动检测前端 JavaScript 库漏洞
开发语言·前端·javascript
扶苏10023 小时前
详解Vue3的自定义 Hooks
前端·javascript·vue.js
二级小助手3 小时前
26年计算机二级web考试介绍【内附真题】
前端·计算机二级·全国计算机二级·web二级·二级web·前端二级·全国计算机web二级
专注VB编程开发20年4 小时前
WebView2 处理跨域访问限制,Frame脚本执行,难度比CEF大10倍
前端·javascript·.net
CHANG_THE_WORLD4 小时前
指针入门一
java·前端·网络
Je1lyfish5 小时前
CMU15-445 (2026 Spring) Project#1 - Buffer Pool Manager
linux·数据库·c++·后端·链表·课程设计·数据库架构
hrhcode5 小时前
【Netty】三.ChannelPipeline与ChannelHandler责任链深度解析
java·后端·spring·springboot·netty
摸鱼仙人~5 小时前
主流前端「语言/技术 → 主流框架 → 组件库生态 → 适用场景」解析
前端