12 KiB
12 KiB
部署和运维文档
🏗️ 部署架构
生产环境架构
┌─────────────┐
│ 用户访问 │
└─────────────┘
│
┌─────────────┐
│ CDN/负载均衡 │
└─────────────┘
│
┌──────────────┼──────────────┐
│ │ │
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ 官网服务 │ │ 管理后台 │ │ 小程序 │
│ (Nginx) │ │ (Nginx) │ │ (CDN) │
└─────────────┘ └─────────────┘ └─────────────┘
│
┌─────────────┐
│ API网关 │
│ (Nginx) │
└─────────────┘
│
┌──────────────┼──────────────┐
│ │ │
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ 后端服务1 │ │ 后端服务2 │ │ 后端服务N │
│ (PM2) │ │ (PM2) │ │ (PM2) │
└─────────────┘ └─────────────┘ └─────────────┘
│
┌──────────────┼──────────────┐
│ │ │
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ MySQL │ │ Redis │ │ 文件存储 │
│ (主从复制) │ │ (集群) │ │ (MinIO) │
└─────────────┘ └─────────────┘ └─────────────┘
🚀 部署流程
1. 服务器准备
基础环境
# 更新系统
sudo apt update && sudo apt upgrade -y
# 安装基础软件
sudo apt install -y nginx nodejs npm mysql-server redis-server git
# 安装Node.js 18
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt-get install -y nodejs
# 安装PM2
sudo npm install -g pm2
目录结构
# 创建项目目录
sudo mkdir -p /var/www/niumall
sudo mkdir -p /var/www/niumall/website
sudo mkdir -p /var/www/niumall/admin
sudo mkdir -p /var/www/niumall/backend
sudo mkdir -p /var/www/niumall/logs
sudo mkdir -p /var/www/niumall/uploads
# 设置权限
sudo chown -R www-data:www-data /var/www/niumall
sudo chmod -R 755 /var/www/niumall
2. 数据库部署
MySQL配置
# 安全配置
sudo mysql_secure_installation
# 创建数据库和用户
mysql -u root -p
-- 创建数据库
CREATE DATABASE jiebandata CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- 创建用户
CREATE USER 'niumall'@'localhost' IDENTIFIED BY 'your_secure_password';
GRANT ALL PRIVILEGES ON jiebandata.* TO 'niumall'@'localhost';
FLUSH PRIVILEGES;
Redis配置
# 编辑Redis配置
sudo vim /etc/redis/redis.conf
# 关键配置项
bind 127.0.0.1
port 6379
requirepass your_redis_password
maxmemory 2gb
maxmemory-policy allkeys-lru
# 重启Redis
sudo systemctl restart redis-server
sudo systemctl enable redis-server
3. 后端服务部署
Node.js版部署
# 克隆代码
cd /var/www/niumall
sudo git clone <repository-url> .
# 安装依赖
cd backend
sudo npm install --production
# 环境配置
sudo cp .env.example .env.production
sudo vim .env.production
Java版部署
# 构建服务
cd /var/www/niumall/backend-java/user-service
sudo ./mvnw clean package
# 运行服务
sudo java -jar target/*.jar --spring.profiles.active=prod
# 或用Docker部署
sudo docker build -t user-service .
sudo docker run -d -p 8081:8081 user-service
环境配置
# .env.production
NODE_ENV=production
PORT=3001
DB_HOST=localhost
DB_PORT=3306
DB_NAME=jiebandata
DB_USER=niumall
DB_PASSWORD=your_secure_password
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=your_redis_password
JWT_SECRET=your_jwt_secret_key
PM2配置
// ecosystem.config.js
module.exports = {
apps: [{
name: 'niumall-backend',
script: 'src/app.js',
cwd: '/var/www/niumall/backend',
instances: 'max',
exec_mode: 'cluster',
env: {
NODE_ENV: 'production',
PORT: 3001
},
error_file: '/var/www/niumall/logs/backend-error.log',
out_file: '/var/www/niumall/logs/backend-out.log',
log_file: '/var/www/niumall/logs/backend.log',
time: true
}]
}
启动后端服务
# 数据库迁移
cd /var/www/niumall/backend
sudo npm run db:migrate
sudo npm run db:seed
# 启动服务
sudo pm2 start ecosystem.config.js
sudo pm2 save
sudo pm2 startup
4. 前端部署
管理后台构建
cd /var/www/niumall/admin-system
sudo npm install
sudo npm run build:prod
# 复制构建文件
sudo cp -r dist/* /var/www/niumall/admin/
官网部署
# 直接复制静态文件
sudo cp -r website/* /var/www/niumall/website/
5. Nginx配置
主配置文件
# /etc/nginx/sites-available/niumall
server {
listen 80;
server_name niumall.com www.niumall.com;
return 301 https://$server_name$request_uri;
}
server {
listen 443 ssl http2;
server_name niumall.com www.niumall.com;
ssl_certificate /path/to/ssl/certificate.crt;
ssl_certificate_key /path/to/ssl/private.key;
# 官网
location / {
root /var/www/niumall/website;
index index.html;
try_files $uri $uri/ /index.html;
}
# 管理后台
location /admin {
alias /var/www/niumall/admin;
index index.html;
try_files $uri $uri/ /admin/index.html;
}
# API接口
location /api {
proxy_pass http://127.0.0.1:3001;
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 /uploads {
alias /var/www/niumall/uploads;
expires 1M;
add_header Cache-Control "public, immutable";
}
}
启用配置
# 创建软链接
sudo ln -s /etc/nginx/sites-available/niumall /etc/nginx/sites-enabled/
# 测试配置
sudo nginx -t
# 重启Nginx
sudo systemctl restart nginx
sudo systemctl enable nginx
🔧 运维管理
1. 监控配置
系统监控
# 安装监控工具
sudo npm install -g pm2-logrotate
sudo pm2 install pm2-server-monit
# 配置日志轮转
sudo pm2 set pm2-logrotate:max_size 10M
sudo pm2 set pm2-logrotate:retain 30
健康检查脚本
#!/bin/bash
# health-check.sh
# 检查后端服务
if curl -f http://localhost:3001/api/health > /dev/null 2>&1; then
echo "✓ Backend service is healthy"
else
echo "✗ Backend service is down"
# 重启服务
pm2 restart niumall-backend
fi
# 检查数据库
if mysqladmin ping -h localhost -u niumall -p'password' --silent; then
echo "✓ MySQL is healthy"
else
echo "✗ MySQL is down"
fi
# 检查Redis
if redis-cli ping > /dev/null 2>&1; then
echo "✓ Redis is healthy"
else
echo "✗ Redis is down"
fi
2. 备份策略
数据库备份
#!/bin/bash
# backup.sh
DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_DIR="/var/backups/niumall"
# 创建备份目录
mkdir -p $BACKUP_DIR
# MySQL备份
mysqldump -u niumall -p'password' jiebandata > $BACKUP_DIR/mysql_$DATE.sql
# 压缩备份
gzip $BACKUP_DIR/mysql_$DATE.sql
# 文件备份
tar -czf $BACKUP_DIR/uploads_$DATE.tar.gz /var/www/niumall/uploads
# 清理老备份(保留30天)
find $BACKUP_DIR -name "*.gz" -mtime +30 -delete
echo "Backup completed: $DATE"
定时任务
# 编辑crontab
sudo crontab -e
# 添加任务
# 每日凌晨2点备份
0 2 * * * /path/to/backup.sh
# 每小时健康检查
0 * * * * /path/to/health-check.sh
# 每日凌晨重启PM2(可选)
0 3 * * 0 pm2 restart all
3. 日志管理
日志配置
# 创建日志目录
sudo mkdir -p /var/log/niumall
# 配置logrotate
sudo vim /etc/logrotate.d/niumall
/var/log/niumall/*.log {
daily
missingok
rotate 30
compress
delaycompress
notifempty
create 644 www-data www-data
}
日志查看命令
# 查看后端日志
sudo pm2 logs niumall-backend
# 查看Nginx日志
sudo tail -f /var/log/nginx/access.log
sudo tail -f /var/log/nginx/error.log
# 查看系统日志
sudo journalctl -u nginx
sudo journalctl -u mysql
4. 性能优化
数据库优化
-- 查看慢查询
SHOW VARIABLES LIKE 'slow_query_log';
SET GLOBAL slow_query_log = 'ON';
SET GLOBAL long_query_time = 1;
-- 分析查询性能
EXPLAIN SELECT * FROM orders WHERE status = 'pending';
-- 添加索引
CREATE INDEX idx_orders_status ON orders(status);
CREATE INDEX idx_orders_created_at ON orders(created_at);
Redis优化
# 监控Redis性能
redis-cli --latency-history -i 1
# 查看内存使用
redis-cli info memory
# 清理过期key
redis-cli --scan --pattern "expired:*" | xargs redis-cli del
🚨 故障处理
常见问题排查
服务无法启动
# 检查端口占用
sudo netstat -tlnp | grep :3001
# 检查进程状态
sudo pm2 status
# 查看错误日志
sudo pm2 logs niumall-backend --err
# 重启服务
sudo pm2 restart niumall-backend
数据库连接失败
# 检查MySQL状态
sudo systemctl status mysql
# 检查连接数
mysql -u root -p -e "SHOW PROCESSLIST;"
# 重启MySQL
sudo systemctl restart mysql
内存不足
# 查看内存使用
free -h
sudo ps aux --sort=-%mem | head
# 清理缓存
sudo sync && echo 3 | sudo tee /proc/sys/vm/drop_caches
# 重启占用内存大的进程
sudo pm2 restart all
紧急恢复流程
数据库恢复
# 停止应用
sudo pm2 stop all
# 恢复数据库
mysql -u root -p jiebandata < /var/backups/niumall/mysql_20240120.sql
# 重启应用
sudo pm2 start all
代码回滚
# 查看提交历史
cd /var/www/niumall
sudo git log --oneline -10
# 回滚到指定版本
sudo git reset --hard <commit-hash>
# 重新部署
cd backend && sudo npm run build
sudo pm2 restart all
📊 监控指标
关键指标
- 服务可用性: > 99.9%
- 响应时间: < 200ms (API), < 3s (页面)
- 错误率: < 0.1%
- CPU使用率: < 70%
- 内存使用率: < 80%
- 磁盘使用率: < 85%
告警配置
# CPU使用率告警
if [ $(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | cut -d'%' -f1) > 70 ]; then
echo "High CPU usage detected" | mail -s "Server Alert" admin@niumall.com
fi
# 磁盘空间告警
if [ $(df / | tail -1 | awk '{print $5}' | cut -d'%' -f1) > 85 ]; then
echo "Low disk space" | mail -s "Storage Alert" admin@niumall.com
fi
📞 运维联系方式
- 运维负责人: ops@niumall.com
- 紧急联系: +86 138-xxxx-xxxx
- 技术支持: tech@niumall.com
- 监控告警: alert@niumall.com