Skip to content

环境配置和部署指南

本指南详细说明了源丰后端API的环境配置、部署流程和运维监控,帮助您在不同环境中正确部署和运行系统。

📋 概述

源丰后端支持多种部署方式,包括本地开发、测试环境、生产环境等。本文档涵盖了从开发到生产的完整部署流程。

🌍 环境分类

环境类型

环境用途域名数据库说明
Development开发调试localhost:8080SQLite/MySQL本地开发环境
Testing功能测试test-api.yuanfeng.comMySQL测试环境
Staging预发布验证staging-api.yuanfeng.comMySQL生产镜像环境
Production正式运行api.yuanfeng.comMySQL生产环境

环境配置优先级

  1. 命令行参数 (最高优先级)
  2. 环境变量
  3. 配置文件 (.env)
  4. 默认值 (最低优先级)

⚙️ 环境变量配置

必需配置项

bash
# 应用配置
APP_PORT=8080                    # 应用端口
APP_HOST=0.0.0.0                 # 监听地址
APP_ENV=production               # 运行环境: development/testing/staging/production
APP_DEBUG=false                  # 调试模式

# 数据库配置
DB_TYPE=mysql                    # 数据库类型: mysql/postgresql/sqlite
DB_HOST=localhost                # 数据库主机
DB_PORT=3306                     # 数据库端口
DB_NAME=yuanfeng_backend         # 数据库名称
DB_USER=root                     # 数据库用户名
DB_PASSWORD=your_password        # 数据库密码
DB_CHARSET=utf8mb4               # 字符集
DB_MAX_OPEN_CONNS=100            # 最大连接数
DB_MAX_IDLE_CONNS=10             # 最大空闲连接数

# JWT配置
JWT_SECRET=your-secret-key       # JWT密钥(必须设置)
JWT_EXPIRES_IN=24h               # Token过期时间
JWT_REFRESH_EXPIRES_IN=168h      # 刷新Token过期时间

# Redis配置(可选)
REDIS_HOST=localhost             # Redis主机
REDIS_PORT=6379                  # Redis端口
REDIS_PASSWORD=                  # Redis密码
REDIS_DB=0                       # Redis数据库
REDIS_POOL_SIZE=10               # 连接池大小

# OSS配置(可选)
OSS_TYPE=aliyun                  # OSS类型: aliyun/tencent/aws
OSS_ACCESS_KEY_ID=your_key       # 访问密钥ID
OSS_ACCESS_KEY_SECRET=your_secret # 访问密钥Secret
OSS_BUCKET=yuanfeng-files        # 存储桶名称
OSS_ENDPOINT=https://oss-cn-beijing.aliyuncs.com # OSS端点
OSS_DOMAIN=https://files.yuanfeng.com # 自定义域名

# 日志配置
LOG_LEVEL=info                   # 日志级别: debug/info/warn/error
LOG_FILE=logs/app.log            # 日志文件路径
LOG_MAX_SIZE=100                 # 日志文件最大大小(MB)
LOG_MAX_BACKUPS=5                # 日志文件备份数量
LOG_MAX_AGE=30                   # 日志文件保留天数

# 邮件配置(可选)
SMTP_HOST=smtp.example.com       # SMTP服务器
SMTP_PORT=587                     # SMTP端口
SMTP_USERNAME=noreply@example.com # SMTP用户名
SMTP_PASSWORD=your_email_password # SMTP密码
SMTP_FROM=源丰系统<noreply@example.com> # 发件人

# 安全配置
CORS_ORIGINS=http://localhost:3000,https://yuanfeng.com # 允许的跨域源
RATE_LIMIT_ENABLED=true          # 是否启用限流
RATE_LIMIT_REQUESTS=1000         # 限流请求数
RATE_LIMIT_WINDOW=1h             # 限流时间窗口

可选配置项

bash
# 监控配置
METRICS_ENABLED=true             # 是否启用监控指标
METRICS_PORT=9090                # 监控端口
HEALTH_CHECK_ENABLED=true        # 是否启用健康检查

# 缓存配置
CACHE_ENABLED=true               # 是否启用缓存
CACHE_TTL=300                    # 缓存过期时间(秒)
CACHE_CLEANUP_INTERVAL=600       # 缓存清理间隔(秒)

# 文件上传配置
UPLOAD_MAX_SIZE=10485760         # 最大上传文件大小(字节)
UPLOAD_ALLOWED_TYPES=jpg,jpeg,png,pdf,doc,docx,xls,xlsx # 允许的文件类型
UPLOAD_TEMP_DIR=temp             # 临时文件目录

# API配置
API_VERSION=v1                   # API版本
API_PREFIX=/api                  # API前缀
API_TIMEOUT=30s                  # API超时时间
API_MAX_REQUEST_SIZE=10485760    # 最大请求大小

🐳 Docker 部署

Dockerfile

dockerfile
# 多阶段构建
FROM golang:1.21-alpine AS builder

# 设置工作目录
WORKDIR /app

# 复制go mod文件
COPY go.mod go.sum ./

# 下载依赖
RUN go mod download

# 复制源代码
COPY . .

# 构建应用
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o main cmd/server/main.go

# 运行阶段
FROM alpine:latest

# 安装ca证书和时区数据
RUN apk --no-cache add ca-certificates tzdata

# 设置工作目录
WORKDIR /root/

# 从构建阶段复制二进制文件
COPY --from=builder /app/main .

# 复制配置文件
COPY .env.example .env

# 创建必要目录
RUN mkdir -p logs temp uploads

# 暴露端口
EXPOSE 8080

# 运行应用
CMD ["./main"]

docker-compose.yml

yaml
version: '3.8'

services:
  app:
    build: .
    container_name: yuanfeng-backend
    ports:
      - "8080:8080"
    environment:
      - APP_ENV=production
      - DB_HOST=mysql
      - REDIS_HOST=redis
    depends_on:
      - mysql
      - redis
    volumes:
      - ./logs:/root/logs
      - ./uploads:/root/uploads
    restart: unless-stopped
    networks:
      - yuanfeng-network

  mysql:
    image: mysql:8.0
    container_name: yuanfeng-mysql
    environment:
      - MYSQL_ROOT_PASSWORD=rootpassword
      - MYSQL_DATABASE=yuanfeng_backend
      - MYSQL_USER=yuanfeng
      - MYSQL_PASSWORD=yuanfeng123
    ports:
      - "3306:3306"
    volumes:
      - mysql_data:/var/lib/mysql
      - ./scripts/init.sql:/docker-entrypoint-initdb.d/init.sql
    restart: unless-stopped
    networks:
      - yuanfeng-network

  redis:
    image: redis:7-alpine
    container_name: yuanfeng-redis
    ports:
      - "6379:6379"
    volumes:
      - redis_data:/data
    restart: unless-stopped
    networks:
      - yuanfeng-network

  nginx:
    image: nginx:alpine
    container_name: yuanfeng-nginx
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./nginx/nginx.conf:/etc/nginx/nginx.conf
      - ./nginx/ssl:/etc/nginx/ssl
    depends_on:
      - app
    restart: unless-stopped
    networks:
      - yuanfeng-network

volumes:
  mysql_data:
  redis_data:

networks:
  yuanfeng-network:
    driver: bridge

部署命令

bash
# 构建并启动服务
docker-compose up -d

# 查看服务状态
docker-compose ps

# 查看日志
docker-compose logs -f app

# 停止服务
docker-compose down

# 重新构建
docker-compose build --no-cache

🚀 Kubernetes 部署

namespace.yaml

yaml
apiVersion: v1
kind: Namespace
metadata:
  name: yuanfeng

configmap.yaml

yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: yuanfeng-config
  namespace: yuanfeng
data:
  APP_ENV: "production"
  DB_HOST: "mysql-service"
  DB_NAME: "yuanfeng_backend"
  REDIS_HOST: "redis-service"
  LOG_LEVEL: "info"

secret.yaml

yaml
apiVersion: v1
kind: Secret
metadata:
  name: yuanfeng-secret
  namespace: yuanfeng
type: Opaque
data:
  db-password: <base64-encoded-password>
  jwt-secret: <base64-encoded-jwt-secret>
  oss-access-key: <base64-encoded-access-key>
  oss-secret-key: <base64-encoded-secret-key>

deployment.yaml

yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: yuanfeng-backend
  namespace: yuanfeng
spec:
  replicas: 3
  selector:
    matchLabels:
      app: yuanfeng-backend
  template:
    metadata:
      labels:
        app: yuanfeng-backend
    spec:
      containers:
      - name: yuanfeng-backend
        image: yuanfeng/backend:latest
        ports:
        - containerPort: 8080
        env:
        - name: DB_PASSWORD
          valueFrom:
            secretKeyRef:
              name: yuanfeng-secret
              key: db-password
        - name: JWT_SECRET
          valueFrom:
            secretKeyRef:
              name: yuanfeng-secret
              key: jwt-secret
        envFrom:
        - configMapRef:
            name: yuanfeng-config
        resources:
          requests:
            memory: "256Mi"
            cpu: "250m"
          limits:
            memory: "512Mi"
            cpu: "500m"
        livenessProbe:
          httpGet:
            path: /health
            port: 8080
          initialDelaySeconds: 30
          periodSeconds: 10
        readinessProbe:
          httpGet:
            path: /health
            port: 8080
          initialDelaySeconds: 5
          periodSeconds: 5

service.yaml

yaml
apiVersion: v1
kind: Service
metadata:
  name: yuanfeng-backend-service
  namespace: yuanfeng
spec:
  selector:
    app: yuanfeng-backend
  ports:
  - protocol: TCP
    port: 80
    targetPort: 8080
  type: ClusterIP

ingress.yaml

yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: yuanfeng-backend-ingress
  namespace: yuanfeng
  annotations:
    kubernetes.io/ingress.class: nginx
    cert-manager.io/cluster-issuer: letsencrypt-prod
    nginx.ingress.kubernetes.io/rate-limit: "100"
spec:
  tls:
  - hosts:
    - api.yuanfeng.com
    secretName: yuanfeng-tls
  rules:
  - host: api.yuanfeng.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: yuanfeng-backend-service
            port:
              number: 80

部署命令

bash
# 应用所有配置
kubectl apply -f k8s/

# 查看部署状态
kubectl get pods -n yuanfeng

# 查看服务状态
kubectl get services -n yuanfeng

# 查看日志
kubectl logs -f deployment/yuanfeng-backend -n yuanfeng

# 扩容
kubectl scale deployment yuanfeng-backend --replicas=5 -n yuanfeng

🔧 传统部署

系统要求

  • 操作系统: Linux (CentOS 7+, Ubuntu 18.04+)
  • CPU: 2核心以上
  • 内存: 4GB以上
  • 存储: 20GB以上
  • 网络: 公网IP或内网访问

安装步骤

1. 环境准备

bash
# 更新系统
sudo apt update && sudo apt upgrade -y

# 安装必要软件
sudo apt install -y git curl wget vim

# 安装Go (以Go 1.21为例)
wget https://go.dev/dl/go1.21.0.linux-amd64.tar.gz
sudo tar -C /usr/local -xzf go1.21.0.linux-amd64.tar.gz
echo 'export PATH=$PATH:/usr/local/go/bin' >> ~/.bashrc
source ~/.bashrc

# 验证安装
go version

2. 数据库安装

bash
# 安装MySQL
sudo apt install -y mysql-server

# 安全配置
sudo mysql_secure_installation

# 创建数据库和用户
mysql -u root -p << EOF
CREATE DATABASE yuanfeng_backend CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER 'yuanfeng'@'localhost' IDENTIFIED BY 'your_password';
GRANT ALL PRIVILEGES ON yuanfeng_backend.* TO 'yuanfeng'@'localhost';
FLUSH PRIVILEGES;
EOF

3. 应用部署

bash
# 克隆代码
git clone https://github.com/your-org/yuanfeng-backend.git
cd yuanfeng-backend

# 安装依赖
go mod download

# 复制配置文件
cp .env.example .env
vim .env  # 编辑配置文件

# 构建应用
go build -o yuanfeng-backend cmd/server/main.go

# 创建systemd服务文件
sudo vim /etc/systemd/system/yuanfeng-backend.service

4. Systemd服务配置

ini
[Unit]
Description=Yuanfeng Backend API
After=network.target mysql.service

[Service]
Type=simple
User=yuanfeng
WorkingDirectory=/opt/yuanfeng-backend
ExecStart=/opt/yuanfeng-backend/yuanfeng-backend
Restart=always
RestartSec=5
Environment=APP_ENV=production

[Install]
WantedBy=multi-user.target

5. 启动服务

bash
# 创建应用用户
sudo useradd -m -s /bin/bash yuanfeng

# 复制应用文件
sudo cp -r . /opt/yuanfeng-backend/
sudo chown -R yuanfeng:yuanfeng /opt/yuanfeng-backend

# 启动服务
sudo systemctl daemon-reload
sudo systemctl enable yuanfeng-backend
sudo systemctl start yuanfeng-backend

# 查看状态
sudo systemctl status yuanfeng-backend

# 查看日志
sudo journalctl -u yuanfeng-backend -f

🔒 安全配置

Nginx反向代理

nginx
server {
    listen 80;
    server_name api.yuanfeng.com;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    server_name api.yuanfeng.com;

    # SSL配置
    ssl_certificate /etc/nginx/ssl/yuanfeng.com.crt;
    ssl_certificate_key /etc/nginx/ssl/yuanfeng.com.key;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512;
    ssl_prefer_server_ciphers off;

    # 安全头
    add_header X-Frame-Options DENY;
    add_header X-Content-Type-Options nosniff;
    add_header X-XSS-Protection "1; mode=block";
    add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload";

    # 限流配置
    limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
    limit_req zone=api burst=20 nodelay;

    # 代理配置
    location / {
        proxy_pass http://127.0.0.1:8080;
        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_connect_timeout 30s;
        proxy_send_timeout 30s;
        proxy_read_timeout 30s;

        # 缓冲配置
        proxy_buffering on;
        proxy_buffer_size 4k;
        proxy_buffers 8 4k;
    }

    # 静态文件
    location /static/ {
        alias /opt/yuanfeng-backend/static/;
        expires 1y;
        add_header Cache-Control "public, immutable";
    }

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

防火墙配置

bash
# UFW防火墙配置
sudo ufw enable
sudo ufw allow ssh
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw deny 8080/tcp  # 禁止直接访问应用端口

# iptables配置
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 8080 -s 127.0.0.1 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 8080 -j DROP

📊 监控和日志

Prometheus监控配置

yaml
# prometheus.yml
global:
  scrape_interval: 15s

scrape_configs:
  - job_name: 'yuanfeng-backend'
    static_configs:
      - targets: ['localhost:9090']
    metrics_path: '/metrics'
    scrape_interval: 5s

Grafana仪表盘

json
{
  "dashboard": {
    "title": "源丰后端监控",
    "panels": [
      {
        "title": "请求QPS",
        "type": "graph",
        "targets": [
          {
            "expr": "rate(http_requests_total[5m])",
            "legendFormat": "{{method}} {{endpoint}}"
          }
        ]
      },
      {
        "title": "响应时间",
        "type": "graph",
        "targets": [
          {
            "expr": "histogram_quantile(0.95, rate(http_request_duration_seconds_bucket[5m]))",
            "legendFormat": "95th percentile"
          }
        ]
      }
    ]
  }
}

日志管理

bash
# logrotate配置
/opt/yuanfeng-backend/logs/*.log {
    daily
    missingok
    rotate 30
    compress
    delaycompress
    notifempty
    create 644 yuanfeng yuanfeng
    postrotate
        systemctl reload yuanfeng-backend
    endscript
}

🔄 数据库管理

数据库备份脚本

bash
#!/bin/bash
# backup.sh

BACKUP_DIR="/opt/backups/mysql"
DATE=$(date +%Y%m%d_%H%M%S)
DB_NAME="yuanfeng_backend"

# 创建备份目录
mkdir -p $BACKUP_DIR

# 备份数据库
mysqldump -u yuanfeng -p$DB_PASSWORD $DB_NAME | gzip > $BACKUP_DIR/yuanfeng_$DATE.sql.gz

# 删除7天前的备份
find $BACKUP_DIR -name "*.sql.gz" -mtime +7 -delete

echo "数据库备份完成: yuanfeng_$DATE.sql.gz"

数据库恢复

bash
#!/bin/bash
# restore.sh

BACKUP_FILE=$1
DB_NAME="yuanfeng_backend"

if [ -z "$BACKUP_FILE" ]; then
    echo "用法: $0 <backup_file>"
    exit 1
fi

# 恢复数据库
gunzip < $BACKUP_FILE | mysql -u yuanfeng -p $DB_NAME

echo "数据库恢复完成"

🚦 健康检查和故障排除

健康检查端点

bash
# 基础健康检查
curl http://localhost:8080/health

# 详细健康检查
curl http://localhost:8080/health/detailed

# 就绪检查
curl http://localhost:8080/health/ready

常见问题排除

1. 数据库连接失败

bash
# 检查数据库状态
sudo systemctl status mysql

# 测试连接
mysql -h localhost -u yuanfeng -p yuanfeng_backend

# 查看错误日志
sudo tail -f /var/log/mysql/error.log

2. 应用启动失败

bash
# 查看应用状态
sudo systemctl status yuanfeng-backend

# 查看详细日志
sudo journalctl -u yuanfeng-backend -n 100

# 检查配置文件
sudo -u yuanfeng cat /opt/yuanfeng-backend/.env

3. 性能问题

bash
# 查看系统资源
top
htop
iostat

# 查看网络连接
netstat -tlnp | grep :8080

# 分析慢查询
mysql -u yuanfeng -p -e "SHOW PROCESSLIST;"

📋 部署检查清单

部署前检查

  • [ ] 环境变量配置完整
  • [ ] 数据库连接测试通过
  • [ ] SSL证书配置正确
  • [ ] 防火墙规则设置
  • [ ] 备份策略制定
  • [ ] 监控系统配置
  • [ ] 日志轮转配置

部署后验证

  • [ ] 应用启动正常
  • [ ] 健康检查通过
  • [ ] 数据库连接正常
  • [ ] API接口响应正常
  • [ ] 日志记录正常
  • [ ] 监控指标正常
  • [ ] 备份任务执行

最后更新: 2024-01-24 文档版本: v1.0 维护团队: 源丰后端开发团队

基于 MIT 许可发布