Some checks failed
Deploy to Production / Run Tests (push) Failing after 16m35s
Deploy to Production / Security Scan (push) Has been skipped
Deploy to Production / Build Docker Image (push) Has been skipped
Deploy to Production / Deploy to Staging (push) Has been skipped
Deploy to Production / Deploy to Production (push) Has been skipped
Deploy to Production / Notify Results (push) Successful in 31s
✨ 新功能: - SQLite数据库集成和持久化存储 - 数据库迁移系统和版本管理 - API分页功能和高效查询 - 用户搜索和过滤机制 - 完整的RBAC角色权限系统 - 结构化日志记录和系统监控 - API限流和多层安全防护 - Docker容器化和生产部署配置 🔒 安全特性: - JWT认证和授权 - 限流和防暴力破解 - 安全头和CORS配置 - 输入验证和XSS防护 - 审计日志和安全监控 📊 监控和运维: - Prometheus指标收集 - 健康检查和系统监控 - 自动化备份和恢复 - 完整的运维文档和脚本 - CI/CD流水线配置 🚀 部署支持: - 多环境Docker配置 - 生产环境部署指南 - 性能优化和安全加固 - 故障排除和应急响应 - 自动化运维脚本 📚 文档完善: - API使用文档 - 部署检查清单 - 运维操作手册 - 性能和安全指南 - 故障排除指南
608 lines
12 KiB
Markdown
608 lines
12 KiB
Markdown
# 生产环境部署指南
|
||
|
||
## 概述
|
||
|
||
本文档提供Rust User API在生产环境中的完整部署指南,包括安全配置、性能优化、监控设置和运维最佳实践。
|
||
|
||
## 🏗️ 架构概览
|
||
|
||
### 推荐架构
|
||
|
||
```
|
||
Internet
|
||
↓
|
||
[Load Balancer/CDN]
|
||
↓
|
||
[Reverse Proxy (Nginx/Traefik)]
|
||
↓
|
||
[Rust User API Containers]
|
||
↓
|
||
[SQLite/PostgreSQL Database]
|
||
```
|
||
|
||
### 组件说明
|
||
|
||
- **负载均衡器**: 分发流量,提供高可用性
|
||
- **反向代理**: SSL终止,静态文件服务,安全过滤
|
||
- **应用容器**: 多实例部署,水平扩展
|
||
- **数据库**: 持久化存储,支持备份恢复
|
||
|
||
## 🔧 生产环境配置
|
||
|
||
### 1. 环境变量配置
|
||
|
||
创建生产环境配置文件:
|
||
|
||
```bash
|
||
# .env.production
|
||
# 服务器配置
|
||
SERVER_HOST=0.0.0.0
|
||
SERVER_PORT=3000
|
||
RUST_LOG=info
|
||
|
||
# 数据库配置
|
||
DATABASE_URL=sqlite:///app/data/production.db?mode=rwc
|
||
# 或使用PostgreSQL
|
||
# DATABASE_URL=postgresql://user:password@db:5432/rust_api
|
||
|
||
# 安全配置
|
||
JWT_SECRET=your-super-secure-jwt-secret-key-change-this
|
||
SECURITY_RATE_LIMIT_PER_MINUTE=100
|
||
SECURITY_BRUTE_FORCE_MAX_ATTEMPTS=5
|
||
SECURITY_BAN_DURATION=3600
|
||
|
||
# 日志配置
|
||
LOG_LEVEL=info
|
||
LOG_FORMAT=json
|
||
LOG_TO_CONSOLE=true
|
||
LOG_TO_FILE=true
|
||
LOG_FILE_PATH=/app/logs/app.log
|
||
|
||
# 监控配置
|
||
METRICS_ENABLED=true
|
||
HEALTH_CHECK_ENABLED=true
|
||
```
|
||
|
||
### 2. Docker Compose 生产配置
|
||
|
||
```yaml
|
||
# docker-compose.prod.yml
|
||
version: '3.8'
|
||
|
||
services:
|
||
rust-user-api:
|
||
build:
|
||
context: .
|
||
dockerfile: Dockerfile
|
||
image: rust-user-api:latest
|
||
container_name: rust-user-api-prod
|
||
restart: always
|
||
ports:
|
||
- "127.0.0.1:3000:3000" # 仅本地访问
|
||
environment:
|
||
- RUST_LOG=info
|
||
- DATABASE_URL=sqlite:///app/data/production.db?mode=rwc
|
||
- JWT_SECRET=${JWT_SECRET}
|
||
- LOG_FORMAT=json
|
||
- LOG_TO_FILE=true
|
||
volumes:
|
||
- api_data:/app/data
|
||
- api_logs:/app/logs
|
||
networks:
|
||
- api_network
|
||
deploy:
|
||
resources:
|
||
limits:
|
||
cpus: '2.0'
|
||
memory: 1G
|
||
reservations:
|
||
cpus: '0.5'
|
||
memory: 256M
|
||
healthcheck:
|
||
test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
|
||
interval: 30s
|
||
timeout: 10s
|
||
retries: 3
|
||
start_period: 40s
|
||
logging:
|
||
driver: "json-file"
|
||
options:
|
||
max-size: "100m"
|
||
max-file: "5"
|
||
|
||
nginx:
|
||
image: nginx:alpine
|
||
container_name: nginx-proxy
|
||
restart: always
|
||
ports:
|
||
- "80:80"
|
||
- "443:443"
|
||
volumes:
|
||
- ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
|
||
- ./nginx/ssl:/etc/nginx/ssl:ro
|
||
- api_logs:/var/log/api:ro
|
||
depends_on:
|
||
- rust-user-api
|
||
networks:
|
||
- api_network
|
||
|
||
volumes:
|
||
api_data:
|
||
driver: local
|
||
api_logs:
|
||
driver: local
|
||
|
||
networks:
|
||
api_network:
|
||
driver: bridge
|
||
```
|
||
|
||
### 3. Nginx 反向代理配置
|
||
|
||
```nginx
|
||
# nginx/nginx.conf
|
||
events {
|
||
worker_connections 1024;
|
||
}
|
||
|
||
http {
|
||
upstream rust_api {
|
||
server rust-user-api:3000;
|
||
# 多实例负载均衡
|
||
# server rust-user-api-2:3000;
|
||
# server rust-user-api-3:3000;
|
||
}
|
||
|
||
# 限流配置
|
||
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
|
||
limit_conn_zone $binary_remote_addr zone=conn_limit_per_ip:10m;
|
||
|
||
server {
|
||
listen 80;
|
||
server_name your-domain.com;
|
||
|
||
# 重定向到HTTPS
|
||
return 301 https://$server_name$request_uri;
|
||
}
|
||
|
||
server {
|
||
listen 443 ssl http2;
|
||
server_name your-domain.com;
|
||
|
||
# SSL配置
|
||
ssl_certificate /etc/nginx/ssl/cert.pem;
|
||
ssl_certificate_key /etc/nginx/ssl/key.pem;
|
||
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=api burst=20 nodelay;
|
||
limit_conn conn_limit_per_ip 10;
|
||
|
||
# API代理
|
||
location /api/ {
|
||
proxy_pass http://rust_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;
|
||
|
||
# 超时配置
|
||
proxy_connect_timeout 30s;
|
||
proxy_send_timeout 30s;
|
||
proxy_read_timeout 30s;
|
||
}
|
||
|
||
# 健康检查
|
||
location /health {
|
||
proxy_pass http://rust_api;
|
||
access_log off;
|
||
}
|
||
|
||
# 监控端点(限制访问)
|
||
location /monitoring/ {
|
||
allow 10.0.0.0/8;
|
||
allow 172.16.0.0/12;
|
||
allow 192.168.0.0/16;
|
||
deny all;
|
||
|
||
proxy_pass http://rust_api;
|
||
}
|
||
}
|
||
}
|
||
```
|
||
|
||
## 🔒 安全配置
|
||
|
||
### 1. SSL/TLS 证书
|
||
|
||
```bash
|
||
# 使用Let's Encrypt获取免费证书
|
||
certbot --nginx -d your-domain.com
|
||
|
||
# 或使用自签名证书(仅测试)
|
||
openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
|
||
-keyout nginx/ssl/key.pem \
|
||
-out nginx/ssl/cert.pem
|
||
```
|
||
|
||
### 2. 防火墙配置
|
||
|
||
```bash
|
||
# UFW配置示例
|
||
ufw default deny incoming
|
||
ufw default allow outgoing
|
||
ufw allow ssh
|
||
ufw allow 80/tcp
|
||
ufw allow 443/tcp
|
||
ufw enable
|
||
```
|
||
|
||
### 3. 系统安全
|
||
|
||
```bash
|
||
# 创建专用用户
|
||
useradd -r -s /bin/false -m -d /opt/rust-api apiuser
|
||
|
||
# 设置文件权限
|
||
chown -R apiuser:apiuser /opt/rust-api
|
||
chmod 750 /opt/rust-api
|
||
```
|
||
|
||
## 📊 监控和日志
|
||
|
||
### 1. Prometheus 配置
|
||
|
||
```yaml
|
||
# monitoring/prometheus.yml
|
||
global:
|
||
scrape_interval: 15s
|
||
|
||
scrape_configs:
|
||
- job_name: 'rust-user-api'
|
||
static_configs:
|
||
- targets: ['rust-user-api:3000']
|
||
metrics_path: '/monitoring/metrics/prometheus'
|
||
scrape_interval: 30s
|
||
|
||
- job_name: 'nginx'
|
||
static_configs:
|
||
- targets: ['nginx:9113']
|
||
```
|
||
|
||
### 2. Grafana 仪表板
|
||
|
||
```json
|
||
{
|
||
"dashboard": {
|
||
"title": "Rust User API Dashboard",
|
||
"panels": [
|
||
{
|
||
"title": "Request Rate",
|
||
"type": "graph",
|
||
"targets": [
|
||
{
|
||
"expr": "rate(http_requests_total[5m])"
|
||
}
|
||
]
|
||
},
|
||
{
|
||
"title": "Response Time",
|
||
"type": "graph",
|
||
"targets": [
|
||
{
|
||
"expr": "histogram_quantile(0.95, rate(http_request_duration_seconds_bucket[5m]))"
|
||
}
|
||
]
|
||
}
|
||
]
|
||
}
|
||
}
|
||
```
|
||
|
||
### 3. 日志聚合
|
||
|
||
```yaml
|
||
# docker-compose.logging.yml
|
||
version: '3.8'
|
||
|
||
services:
|
||
elasticsearch:
|
||
image: docker.elastic.co/elasticsearch/elasticsearch:7.15.0
|
||
environment:
|
||
- discovery.type=single-node
|
||
volumes:
|
||
- es_data:/usr/share/elasticsearch/data
|
||
|
||
logstash:
|
||
image: docker.elastic.co/logstash/logstash:7.15.0
|
||
volumes:
|
||
- ./logstash/pipeline:/usr/share/logstash/pipeline
|
||
- api_logs:/logs
|
||
|
||
kibana:
|
||
image: docker.elastic.co/kibana/kibana:7.15.0
|
||
ports:
|
||
- "5601:5601"
|
||
environment:
|
||
- ELASTICSEARCH_HOSTS=http://elasticsearch:9200
|
||
|
||
volumes:
|
||
es_data:
|
||
```
|
||
|
||
## 🚀 部署流程
|
||
|
||
### 1. 自动化部署脚本
|
||
|
||
```bash
|
||
#!/bin/bash
|
||
# deploy.sh
|
||
|
||
set -e
|
||
|
||
echo "🚀 开始部署 Rust User API..."
|
||
|
||
# 1. 拉取最新代码
|
||
git pull origin main
|
||
|
||
# 2. 构建镜像
|
||
docker-compose -f docker-compose.prod.yml build --no-cache
|
||
|
||
# 3. 备份数据库
|
||
docker-compose -f docker-compose.prod.yml exec rust-user-api \
|
||
cp /app/data/production.db /app/data/backup-$(date +%Y%m%d-%H%M%S).db
|
||
|
||
# 4. 停止旧服务
|
||
docker-compose -f docker-compose.prod.yml down
|
||
|
||
# 5. 启动新服务
|
||
docker-compose -f docker-compose.prod.yml up -d
|
||
|
||
# 6. 健康检查
|
||
sleep 30
|
||
if curl -f http://localhost/health; then
|
||
echo "✅ 部署成功!"
|
||
else
|
||
echo "❌ 部署失败,回滚..."
|
||
docker-compose -f docker-compose.prod.yml down
|
||
# 这里可以添加回滚逻辑
|
||
exit 1
|
||
fi
|
||
|
||
echo "🎉 部署完成!"
|
||
```
|
||
|
||
### 2. CI/CD 流水线
|
||
|
||
```yaml
|
||
# .github/workflows/deploy.yml
|
||
name: Deploy to Production
|
||
|
||
on:
|
||
push:
|
||
branches: [main]
|
||
|
||
jobs:
|
||
deploy:
|
||
runs-on: ubuntu-latest
|
||
steps:
|
||
- uses: actions/checkout@v2
|
||
|
||
- name: Setup Docker
|
||
uses: docker/setup-buildx-action@v1
|
||
|
||
- name: Build and test
|
||
run: |
|
||
docker build -t rust-user-api:test .
|
||
docker run --rm rust-user-api:test cargo test
|
||
|
||
- name: Deploy to production
|
||
run: |
|
||
ssh ${{ secrets.PROD_SERVER }} 'cd /opt/rust-api && ./deploy.sh'
|
||
```
|
||
|
||
## 📈 性能优化
|
||
|
||
### 1. 数据库优化
|
||
|
||
```sql
|
||
-- SQLite优化
|
||
PRAGMA journal_mode = WAL;
|
||
PRAGMA synchronous = NORMAL;
|
||
PRAGMA cache_size = 1000000;
|
||
PRAGMA temp_store = memory;
|
||
```
|
||
|
||
### 2. 应用优化
|
||
|
||
```toml
|
||
# Cargo.toml 生产优化
|
||
[profile.release]
|
||
opt-level = 3
|
||
lto = true
|
||
codegen-units = 1
|
||
panic = 'abort'
|
||
```
|
||
|
||
### 3. 容器优化
|
||
|
||
```dockerfile
|
||
# 多阶段构建优化
|
||
FROM rust:1.88-slim as builder
|
||
# ... 构建阶段
|
||
|
||
FROM debian:bookworm-slim
|
||
# 安装运行时依赖
|
||
RUN apt-get update && apt-get install -y \
|
||
ca-certificates \
|
||
sqlite3 \
|
||
libssl3 \
|
||
curl \
|
||
&& rm -rf /var/lib/apt/lists/* \
|
||
&& apt-get clean
|
||
```
|
||
|
||
## 🔧 运维管理
|
||
|
||
### 1. 备份策略
|
||
|
||
```bash
|
||
#!/bin/bash
|
||
# backup.sh
|
||
|
||
BACKUP_DIR="/opt/backups"
|
||
DATE=$(date +%Y%m%d-%H%M%S)
|
||
|
||
# 数据库备份
|
||
docker-compose exec rust-user-api \
|
||
sqlite3 /app/data/production.db ".backup /app/data/backup-$DATE.db"
|
||
|
||
# 压缩备份
|
||
tar -czf "$BACKUP_DIR/api-backup-$DATE.tar.gz" \
|
||
-C /opt/rust-api/data backup-$DATE.db
|
||
|
||
# 清理旧备份(保留30天)
|
||
find $BACKUP_DIR -name "api-backup-*.tar.gz" -mtime +30 -delete
|
||
```
|
||
|
||
### 2. 监控告警
|
||
|
||
```yaml
|
||
# alertmanager.yml
|
||
groups:
|
||
- name: rust-api-alerts
|
||
rules:
|
||
- alert: HighErrorRate
|
||
expr: rate(http_requests_total{status=~"5.."}[5m]) > 0.1
|
||
for: 5m
|
||
annotations:
|
||
summary: "High error rate detected"
|
||
|
||
- alert: HighResponseTime
|
||
expr: histogram_quantile(0.95, rate(http_request_duration_seconds_bucket[5m])) > 1
|
||
for: 5m
|
||
annotations:
|
||
summary: "High response time detected"
|
||
```
|
||
|
||
### 3. 日常维护
|
||
|
||
```bash
|
||
# 系统维护脚本
|
||
#!/bin/bash
|
||
|
||
# 清理Docker资源
|
||
docker system prune -f
|
||
|
||
# 更新系统包
|
||
apt update && apt upgrade -y
|
||
|
||
# 检查磁盘空间
|
||
df -h
|
||
|
||
# 检查服务状态
|
||
docker-compose ps
|
||
systemctl status docker
|
||
```
|
||
|
||
## 🔍 故障排除
|
||
|
||
### 1. 常见问题
|
||
|
||
| 问题 | 症状 | 解决方案 |
|
||
|------|------|----------|
|
||
| 内存不足 | 容器重启 | 增加内存限制,优化代码 |
|
||
| 数据库锁定 | 请求超时 | 检查并发连接,优化查询 |
|
||
| SSL证书过期 | HTTPS错误 | 更新证书,配置自动续期 |
|
||
| 磁盘空间不足 | 写入失败 | 清理日志,扩展存储 |
|
||
|
||
### 2. 调试工具
|
||
|
||
```bash
|
||
# 查看容器日志
|
||
docker-compose logs -f rust-user-api
|
||
|
||
# 进入容器调试
|
||
docker-compose exec rust-user-api /bin/bash
|
||
|
||
# 检查网络连接
|
||
docker network ls
|
||
docker network inspect rust-server_api_network
|
||
|
||
# 监控资源使用
|
||
docker stats
|
||
htop
|
||
iotop
|
||
```
|
||
|
||
## 📋 检查清单
|
||
|
||
### 部署前检查
|
||
|
||
- [ ] 环境变量配置正确
|
||
- [ ] SSL证书有效
|
||
- [ ] 防火墙规则配置
|
||
- [ ] 数据库备份完成
|
||
- [ ] 监控系统正常
|
||
- [ ] 负载测试通过
|
||
|
||
### 部署后验证
|
||
|
||
- [ ] 健康检查通过
|
||
- [ ] API端点响应正常
|
||
- [ ] 日志记录正常
|
||
- [ ] 监控指标正常
|
||
- [ ] 安全扫描通过
|
||
- [ ] 性能测试达标
|
||
|
||
## 🎯 最佳实践
|
||
|
||
### 1. 安全最佳实践
|
||
|
||
- 使用强密码和密钥
|
||
- 定期更新依赖包
|
||
- 启用审计日志
|
||
- 实施最小权限原则
|
||
- 定期安全扫描
|
||
|
||
### 2. 性能最佳实践
|
||
|
||
- 启用HTTP/2
|
||
- 使用CDN加速
|
||
- 实施缓存策略
|
||
- 优化数据库查询
|
||
- 监控关键指标
|
||
|
||
### 3. 运维最佳实践
|
||
|
||
- 自动化部署流程
|
||
- 实施蓝绿部署
|
||
- 定期备份数据
|
||
- 监控系统健康
|
||
- 建立应急响应计划
|
||
|
||
---
|
||
|
||
## 📞 支持和维护
|
||
|
||
### 联系信息
|
||
- 技术支持: tech-support@company.com
|
||
- 紧急联系: +86-xxx-xxxx-xxxx
|
||
- 文档更新: docs@company.com
|
||
|
||
### 更新日志
|
||
- v1.0.0: 初始生产环境配置
|
||
- v1.1.0: 添加监控和告警
|
||
- v1.2.0: 优化性能和安全配置
|
||
|
||
---
|
||
|
||
**注意**: 本文档应根据实际生产环境需求进行调整和定制。定期审查和更新配置以确保最佳的安全性和性能。 |