Files
niumalll/docs/部署运维文档.md

992 lines
19 KiB
Markdown
Raw Normal View History

# 活牛采购智能数字化系统 - 部署运维文档
## 概述
本文档详细描述了活牛采购智能数字化系统的部署流程、运维管理、监控告警和故障处理等内容,为系统的稳定运行提供完整的运维指南。
## 环境要求
### 硬件要求
#### 最小配置
- **CPU**: 2核心
- **内存**: 4GB RAM
- **存储**: 50GB SSD
- **网络**: 10Mbps带宽
#### 推荐配置
- **CPU**: 4核心以上
- **内存**: 8GB RAM以上
- **存储**: 100GB SSD以上
- **网络**: 100Mbps带宽以上
#### 生产环境配置
- **CPU**: 8核心以上
- **内存**: 16GB RAM以上
- **存储**: 500GB SSD以上
- **网络**: 1Gbps带宽以上
### 软件要求
#### 操作系统
- **Linux**: Ubuntu 20.04+ / CentOS 8+ / RHEL 8+
- **macOS**: 10.15+ (仅开发环境)
- **Windows**: Windows 10+ (仅开发环境)
#### 运行环境
- **Node.js**: 18.x LTS
- **npm**: 8.x+
- **MySQL**: 8.0+
- **Redis**: 6.x+ (可选)
- **Nginx**: 1.18+ (生产环境)
#### 容器环境
- **Docker**: 20.10+
- **Docker Compose**: 2.0+
## 部署架构
### 单机部署架构
```
┌─────────────────────────────────────────┐
│ 服务器 (单机) │
├─────────────────────────────────────────┤
│ Nginx (反向代理 + 静态文件服务) │
├─────────────────────────────────────────┤
│ Node.js 应用 (PM2管理) │
├─────────────────────────────────────────┤
│ MySQL 数据库 │
├─────────────────────────────────────────┤
│ Redis 缓存 (可选) │
└─────────────────────────────────────────┘
```
### 集群部署架构
```
┌─────────────┐ ┌─────────────────────────────────┐ ┌─────────────┐
│ 负载均衡器 │ │ 应用服务器集群 │ │ 数据库集群 │
│ (Nginx) │◄──►│ ┌─────────┐ ┌─────────┐ │◄──►│ (MySQL) │
│ │ │ │ Node.js │ │ Node.js │ │ │ │
│ │ │ │ App1 │ │ App2 │ │ │ 主从复制 │
└─────────────┘ │ └─────────┘ └─────────┘ │ │ │
│ ┌─────────┐ ┌─────────┐ │ └─────────────┘
│ │ Redis │ │ 文件存储 │ │
│ │ 缓存 │ │ (NFS) │ │
│ └─────────┘ └─────────┘ │
└─────────────────────────────────┘
```
## 部署流程
### 1. 环境准备
#### 1.1 系统更新
```bash
# Ubuntu/Debian
sudo apt update && sudo apt upgrade -y
# CentOS/RHEL
sudo yum update -y
```
#### 1.2 安装Node.js
```bash
# 使用NodeSource仓库安装
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt-get install -y nodejs
# 验证安装
node --version
npm --version
```
#### 1.3 安装MySQL
```bash
# Ubuntu/Debian
sudo apt install mysql-server -y
# 启动并设置开机自启
sudo systemctl start mysql
sudo systemctl enable mysql
# 安全配置
sudo mysql_secure_installation
```
#### 1.4 安装Nginx
```bash
# Ubuntu/Debian
sudo apt install nginx -y
# 启动并设置开机自启
sudo systemctl start nginx
sudo systemctl enable nginx
```
#### 1.5 安装PM2
```bash
# 全局安装PM2
sudo npm install -g pm2
# 设置PM2开机自启
pm2 startup
sudo env PATH=$PATH:/usr/bin /usr/lib/node_modules/pm2/bin/pm2 startup systemd -u $USER --hp $HOME
```
### 2. 代码部署
#### 2.1 创建部署目录
```bash
sudo mkdir -p /var/www/niumall
sudo chown $USER:$USER /var/www/niumall
cd /var/www/niumall
```
#### 2.2 克隆代码
```bash
# 从Git仓库克隆
git clone https://github.com/your-org/niumall.git .
# 或者上传代码包
# scp -r ./niumall user@server:/var/www/
```
#### 2.3 安装依赖
```bash
# 后端依赖
cd backend
npm install --production
# 前端构建
cd ../frontend
npm install
npm run build
```
### 3. 数据库配置
#### 3.1 创建数据库
```sql
-- 登录MySQL
mysql -u root -p
-- 创建数据库
CREATE DATABASE niumall CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- 创建用户
CREATE USER 'niumall'@'localhost' IDENTIFIED BY 'your_password';
GRANT ALL PRIVILEGES ON niumall.* TO 'niumall'@'localhost';
FLUSH PRIVILEGES;
```
#### 3.2 配置环境变量
```bash
# 创建环境配置文件
cd /var/www/niumall/backend
cp .env.example .env
# 编辑配置文件
nano .env
```
```env
# 数据库配置
DB_HOST=localhost
DB_PORT=3306
DB_USERNAME=niumall
DB_PASSWORD=your_password
DB_NAME=niumall
# JWT配置
JWT_SECRET=your_jwt_secret_key
JWT_EXPIRES_IN=24h
# 应用配置
NODE_ENV=production
PORT=3000
```
#### 3.3 初始化数据库
```bash
# 运行数据库迁移
cd /var/www/niumall/backend
npm run migrate
# 创建管理员用户
node create_admin.js
```
### 4. Nginx配置
#### 4.1 创建站点配置
```bash
sudo nano /etc/nginx/sites-available/niumall
```
```nginx
server {
listen 80;
server_name your-domain.com;
# 前端静态文件
location / {
root /var/www/niumall/frontend/dist;
try_files $uri $uri/ /index.html;
# 缓存静态资源
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
}
# API代理
location /api/ {
proxy_pass http://localhost:3000;
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;
}
# 文件上传大小限制
client_max_body_size 10M;
# 安全头
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "no-referrer-when-downgrade" always;
add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always;
}
```
#### 4.2 启用站点
```bash
# 创建软链接
sudo ln -s /etc/nginx/sites-available/niumall /etc/nginx/sites-enabled/
# 测试配置
sudo nginx -t
# 重载配置
sudo systemctl reload nginx
```
### 5. SSL证书配置
#### 5.1 安装Certbot
```bash
# Ubuntu/Debian
sudo apt install certbot python3-certbot-nginx -y
```
#### 5.2 获取SSL证书
```bash
# 自动配置SSL
sudo certbot --nginx -d your-domain.com
# 设置自动续期
sudo crontab -e
# 添加以下行
0 12 * * * /usr/bin/certbot renew --quiet
```
### 6. 应用启动
#### 6.1 PM2配置文件
```bash
cd /var/www/niumall/backend
nano ecosystem.config.js
```
```javascript
module.exports = {
apps: [{
name: 'niumall-api',
script: 'src/main.js',
instances: 'max',
exec_mode: 'cluster',
env: {
NODE_ENV: 'production',
PORT: 3000
},
error_file: '/var/log/niumall/error.log',
out_file: '/var/log/niumall/out.log',
log_file: '/var/log/niumall/combined.log',
time: true,
max_memory_restart: '1G',
node_args: '--max_old_space_size=1024'
}]
};
```
#### 6.2 启动应用
```bash
# 创建日志目录
sudo mkdir -p /var/log/niumall
sudo chown $USER:$USER /var/log/niumall
# 启动应用
pm2 start ecosystem.config.js
# 保存PM2配置
pm2 save
```
## 容器化部署
### 1. Docker部署
#### 1.1 Dockerfile配置
**后端Dockerfile**
```dockerfile
# backend/Dockerfile
FROM node:18-alpine
WORKDIR /app
# 复制package文件
COPY package*.json ./
# 安装依赖
RUN npm ci --only=production
# 复制源代码
COPY . .
# 暴露端口
EXPOSE 3000
# 启动应用
CMD ["npm", "start"]
```
**前端Dockerfile**
```dockerfile
# frontend/Dockerfile
FROM node:18-alpine as builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/nginx.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
```
#### 1.2 Docker Compose配置
```yaml
# docker-compose.yml
version: '3.8'
services:
frontend:
build: ./frontend
ports:
- "80:80"
depends_on:
- backend
networks:
- niumall-network
backend:
build: ./backend
ports:
- "3000:3000"
environment:
- NODE_ENV=production
- DB_HOST=database
- DB_PORT=3306
- DB_USERNAME=niumall
- DB_PASSWORD=password
- DB_NAME=niumall
- JWT_SECRET=your_jwt_secret
depends_on:
- database
networks:
- niumall-network
volumes:
- ./logs:/app/logs
database:
image: mysql:8.0
environment:
- MYSQL_ROOT_PASSWORD=rootpassword
- MYSQL_DATABASE=niumall
- MYSQL_USER=niumall
- MYSQL_PASSWORD=password
ports:
- "3306:3306"
volumes:
- mysql_data:/var/lib/mysql
- ./init.sql:/docker-entrypoint-initdb.d/init.sql
networks:
- niumall-network
redis:
image: redis:6-alpine
ports:
- "6379:6379"
networks:
- niumall-network
volumes:
mysql_data:
networks:
niumall-network:
driver: bridge
```
#### 1.3 部署命令
```bash
# 构建并启动服务
docker-compose up -d
# 查看服务状态
docker-compose ps
# 查看日志
docker-compose logs -f backend
```
### 2. Kubernetes部署
#### 2.1 命名空间
```yaml
# k8s/namespace.yaml
apiVersion: v1
kind: Namespace
metadata:
name: niumall
```
#### 2.2 配置映射
```yaml
# k8s/configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: niumall-config
namespace: niumall
data:
NODE_ENV: "production"
DB_HOST: "mysql-service"
DB_PORT: "3306"
DB_NAME: "niumall"
```
#### 2.3 密钥
```yaml
# k8s/secret.yaml
apiVersion: v1
kind: Secret
metadata:
name: niumall-secret
namespace: niumall
type: Opaque
data:
DB_PASSWORD: <base64-encoded-password>
JWT_SECRET: <base64-encoded-jwt-secret>
```
#### 2.4 部署配置
```yaml
# k8s/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: niumall-backend
namespace: niumall
spec:
replicas: 3
selector:
matchLabels:
app: niumall-backend
template:
metadata:
labels:
app: niumall-backend
spec:
containers:
- name: backend
image: niumall/backend:latest
ports:
- containerPort: 3000
envFrom:
- configMapRef:
name: niumall-config
- secretRef:
name: niumall-secret
resources:
requests:
memory: "256Mi"
cpu: "250m"
limits:
memory: "512Mi"
cpu: "500m"
```
## 监控和日志
### 1. 应用监控
#### 1.1 PM2监控
```bash
# 查看应用状态
pm2 status
# 查看详细信息
pm2 show niumall-api
# 查看日志
pm2 logs niumall-api
# 重启应用
pm2 restart niumall-api
# 重载应用(零停机)
pm2 reload niumall-api
```
#### 1.2 系统监控
```bash
# 安装htop
sudo apt install htop -y
# 查看系统资源
htop
# 查看磁盘使用
df -h
# 查看内存使用
free -h
# 查看网络连接
netstat -tulpn
```
### 2. 日志管理
#### 2.1 日志轮转配置
```bash
# 创建logrotate配置
sudo nano /etc/logrotate.d/niumall
```
```
/var/log/niumall/*.log {
daily
missingok
rotate 30
compress
delaycompress
notifempty
create 644 $USER $USER
postrotate
pm2 reloadLogs
endscript
}
```
#### 2.2 日志分析
```bash
# 查看错误日志
tail -f /var/log/niumall/error.log
# 分析访问日志
tail -f /var/log/nginx/access.log
# 统计API调用
grep "POST /api" /var/log/nginx/access.log | wc -l
```
### 3. 性能监控
#### 3.1 安装监控工具
```bash
# 安装Node.js性能监控
npm install -g clinic
# 使用clinic监控
clinic doctor -- node src/main.js
```
#### 3.2 数据库监控
```sql
-- 查看慢查询
SHOW VARIABLES LIKE 'slow_query_log';
SET GLOBAL slow_query_log = 'ON';
SET GLOBAL long_query_time = 2;
-- 查看连接数
SHOW STATUS LIKE 'Threads_connected';
-- 查看查询缓存
SHOW STATUS LIKE 'Qcache%';
```
## 备份和恢复
### 1. 数据库备份
#### 1.1 自动备份脚本
```bash
#!/bin/bash
# backup.sh
# 配置变量
DB_NAME="niumall"
DB_USER="niumall"
DB_PASS="password"
BACKUP_DIR="/var/backups/mysql"
DATE=$(date +%Y%m%d_%H%M%S)
# 创建备份目录
mkdir -p $BACKUP_DIR
# 执行备份
mysqldump -u$DB_USER -p$DB_PASS $DB_NAME > $BACKUP_DIR/niumall_$DATE.sql
# 压缩备份文件
gzip $BACKUP_DIR/niumall_$DATE.sql
# 删除7天前的备份
find $BACKUP_DIR -name "*.sql.gz" -mtime +7 -delete
echo "Backup completed: niumall_$DATE.sql.gz"
```
#### 1.2 设置定时备份
```bash
# 添加执行权限
chmod +x backup.sh
# 设置定时任务
crontab -e
# 每天凌晨2点执行备份
0 2 * * * /path/to/backup.sh
```
### 2. 文件备份
#### 2.1 代码备份
```bash
#!/bin/bash
# backup_code.sh
APP_DIR="/var/www/niumall"
BACKUP_DIR="/var/backups/code"
DATE=$(date +%Y%m%d_%H%M%S)
mkdir -p $BACKUP_DIR
# 打包代码
tar -czf $BACKUP_DIR/niumall_code_$DATE.tar.gz -C $APP_DIR .
# 删除30天前的备份
find $BACKUP_DIR -name "*.tar.gz" -mtime +30 -delete
```
### 3. 数据恢复
#### 3.1 数据库恢复
```bash
# 解压备份文件
gunzip niumall_20240101_020000.sql.gz
# 恢复数据库
mysql -u niumall -p niumall < niumall_20240101_020000.sql
```
#### 3.2 代码恢复
```bash
# 停止应用
pm2 stop niumall-api
# 备份当前代码
mv /var/www/niumall /var/www/niumall.bak
# 解压备份代码
mkdir /var/www/niumall
tar -xzf niumall_code_20240101_020000.tar.gz -C /var/www/niumall
# 重启应用
pm2 start niumall-api
```
## 安全配置
### 1. 防火墙配置
#### 1.1 UFW配置
```bash
# 启用UFW
sudo ufw enable
# 允许SSH
sudo ufw allow ssh
# 允许HTTP和HTTPS
sudo ufw allow 80
sudo ufw allow 443
# 查看状态
sudo ufw status
```
#### 1.2 iptables配置
```bash
# 基本规则
sudo iptables -A INPUT -i lo -j ACCEPT
sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
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 -j DROP
# 保存规则
sudo iptables-save > /etc/iptables/rules.v4
```
### 2. 系统安全
#### 2.1 SSH安全配置
```bash
# 编辑SSH配置
sudo nano /etc/ssh/sshd_config
# 禁用root登录
PermitRootLogin no
# 修改默认端口
Port 2222
# 禁用密码认证(使用密钥认证)
PasswordAuthentication no
# 重启SSH服务
sudo systemctl restart sshd
```
#### 2.2 系统更新
```bash
# 设置自动安全更新
sudo apt install unattended-upgrades -y
sudo dpkg-reconfigure -plow unattended-upgrades
```
### 3. 应用安全
#### 3.1 文件权限
```bash
# 设置应用目录权限
sudo chown -R www-data:www-data /var/www/niumall
sudo chmod -R 755 /var/www/niumall
# 保护配置文件
sudo chmod 600 /var/www/niumall/backend/.env
```
#### 3.2 Nginx安全配置
```nginx
# 隐藏Nginx版本
server_tokens off;
# 限制请求大小
client_max_body_size 10M;
# 限制请求频率
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
limit_req zone=api burst=20 nodelay;
# 安全头
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header X-Content-Type-Options "nosniff" always;
```
## 故障处理
### 1. 常见问题
#### 1.1 应用无法启动
```bash
# 检查端口占用
sudo netstat -tulpn | grep :3000
# 检查PM2状态
pm2 status
# 查看错误日志
pm2 logs niumall-api --err
# 检查环境变量
pm2 env 0
```
#### 1.2 数据库连接失败
```bash
# 检查MySQL状态
sudo systemctl status mysql
# 测试数据库连接
mysql -u niumall -p -h localhost
# 检查数据库配置
cat /var/www/niumall/backend/.env
```
#### 1.3 Nginx配置错误
```bash
# 测试Nginx配置
sudo nginx -t
# 查看Nginx错误日志
sudo tail -f /var/log/nginx/error.log
# 重载Nginx配置
sudo systemctl reload nginx
```
### 2. 性能问题
#### 2.1 内存不足
```bash
# 查看内存使用
free -h
# 查看进程内存使用
ps aux --sort=-%mem | head
# 重启应用释放内存
pm2 restart niumall-api
```
#### 2.2 磁盘空间不足
```bash
# 查看磁盘使用
df -h
# 清理日志文件
sudo journalctl --vacuum-time=7d
# 清理临时文件
sudo apt autoremove -y
sudo apt autoclean
```
### 3. 应急处理
#### 3.1 服务降级
```bash
# 停止非关键服务
pm2 stop non-critical-service
# 启用维护模式
sudo cp maintenance.html /var/www/html/index.html
```
#### 3.2 快速回滚
```bash
# 回滚到上一个版本
pm2 stop niumall-api
git checkout HEAD~1
npm install
pm2 start niumall-api
```
## 运维脚本
### 1. 健康检查脚本
```bash
#!/bin/bash
# health_check.sh
# 检查应用状态
if ! pm2 describe niumall-api > /dev/null 2>&1; then
echo "Application is down, restarting..."
pm2 restart niumall-api
fi
# 检查数据库连接
if ! mysqladmin ping -h localhost --silent; then
echo "Database is down, please check MySQL service"
sudo systemctl restart mysql
fi
# 检查磁盘空间
DISK_USAGE=$(df / | grep -vE '^Filesystem' | awk '{print $5}' | sed 's/%//g')
if [ $DISK_USAGE -gt 80 ]; then
echo "Disk usage is above 80%: ${DISK_USAGE}%"
fi
```
### 2. 部署脚本
```bash
#!/bin/bash
# deploy.sh
set -e
APP_DIR="/var/www/niumall"
BACKUP_DIR="/var/backups/deployments"
DATE=$(date +%Y%m%d_%H%M%S)
echo "Starting deployment..."
# 创建备份
mkdir -p $BACKUP_DIR
tar -czf $BACKUP_DIR/niumall_$DATE.tar.gz -C $APP_DIR .
# 拉取最新代码
cd $APP_DIR
git pull origin main
# 安装依赖
cd backend
npm install --production
# 运行数据库迁移
npm run migrate
# 构建前端
cd ../frontend
npm install
npm run build
# 重启应用
pm2 reload niumall-api
echo "Deployment completed successfully!"
```
## 总结
本文档提供了活牛采购智能数字化系统的完整部署和运维指南,包括环境准备、代码部署、监控告警、备份恢复、安全配置和故障处理等各个方面。通过遵循本文档的指导,可以确保系统的稳定运行和高效维护。
在实际运维过程中,建议:
1. 定期检查系统状态和性能指标
2. 及时更新系统和应用补丁
3. 定期测试备份和恢复流程
4. 建立完善的监控告警机制
5. 制定详细的应急响应预案
通过持续的运维优化和改进,可以不断提升系统的可靠性和性能表现。