生产环境部署指南

2025-12-04 21:58 更新

生产环境部署指南

本文档介绍如何将 DoraCMS 部署到生产环境,聚焦核心配置和关键步骤。

部署架构

用户请求 → Nginx (SSL) → DoraCMS 应用 (PM2) → 数据库 + Redis

生产环境架构

服务器推荐配置

  • CPU:4核+
  • 内存:8GB+
  • 硬盘:50GB+ SSD

快速部署步骤

1. 准备服务器环境

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


## 安装必需软件
sudo apt install nginx mongodb redis-server -y


## 安装 Node.js 18+
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt install nodejs -y


## 安装 pnpm
npm install -g pnpm


## 安装 PM2
npm install -g pm2

2. 部署应用代码

## 创建应用目录
sudo mkdir -p /var/www/doracms
cd /var/www/doracms


## 克隆代码(或上传代码包)
git clone https://github.com/doramart/DoraCMS.git .


## 安装依赖
pnpm install


## 构建应用
pnpm build

3. 配置环境变量

创建 .env 文件:

## 生产环境
NODE_ENV=production
PORT=8080


## 数据库配置
MONGODB_HOST=127.0.0.1
MONGODB_PORT=27017
MONGODB_DATABASE=doracms3


## Redis 配置
REDIS_HOST=127.0.0.1
REDIS_PORT=6379


## 应用密钥(务必修改)
APP_KEYS=your_production_secret_key_here

4. 配置 Nginx

创建 /etc/nginx/sites-available/doracms

## HTTP 重定向到 HTTPS
server {
    listen 80;
    server_name your-domain.com;
    return 301 https://$server_name$request_uri;
}


## HTTPS 服务器
server {
    listen 443 ssl http2;
    server_name your-domain.com;

    
    # SSL 证书(使用 Let's Encrypt)
    ssl_certificate /etc/letsencrypt/live/your-domain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/your-domain.com/privkey.pem;

    
    # 静态资源
    location /uploads/ {
        alias /var/www/doracms/uploads/;
        expires 30d;
    }

    
    # 用户前端
    location / {
        proxy_pass http://localhost:3000;
        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 /admin {
        proxy_pass http://localhost:5173;
        proxy_set_header Host $host;
    }

    
    # API 接口
    location /api/ {
        proxy_pass http://localhost:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

启用配置:

sudo ln -s /etc/nginx/sites-available/doracms /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx

Nginx 配置

5. 配置 SSL 证书

使用 Let's Encrypt 免费证书:

## 安装 Certbot
sudo apt install certbot python3-certbot-nginx -y


## 获取证书
sudo certbot --nginx -d your-domain.com


## 自动续期
sudo certbot renew --dry-run

6. 使用 PM2 启动应用

创建 ecosystem.config.js

module.exports = {
  apps: [
    {
      name: 'doracms-server',
      script: 'server/app.js',
      instances: 2,
      exec_mode: 'cluster',
      env: {
        NODE_ENV: 'production',
        PORT: 8080
      }
    },
    {
      name: 'doracms-frontend',
      script: 'npm',
      args: 'run start',
      env: {
        NODE_ENV: 'production'
      }
    }
  ]
};

启动应用:

## 启动所有服务
pm2 start ecosystem.config.js


## 设置开机自启
pm2 startup
pm2 save


## 查看状态
pm2 status
pm2 logs

PM2 管理

性能优化

数据库优化

MongoDB 索引

// 在 MongoDB shell 中执行
use doracms3


// 为常用查询创建索引
db.contents.createIndex({state: 1, createdAt: -1})
db.contents.createIndex({categoryId: 1, state: 1})
db.users.createIndex({userName: 1})

连接池配置.env):

DB_POOL_MIN=5
DB_POOL_MAX=20

Redis 缓存

编辑 /etc/redis/redis.conf

maxmemory 2gb
maxmemory-policy allkeys-lru

重启 Redis:

sudo systemctl restart redis

Nginx 优化

在 Nginx 配置中添加:

## Gzip 压缩
gzip on;
gzip_types text/plain text/css application/json application/javascript;


## 静态资源缓存
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
    expires 1y;
    add_header Cache-Control "public, immutable";
}

安全配置

防火墙设置

## 启用 UFW
sudo ufw enable


## 允许必要端口
sudo ufw allow 22/tcp   # SSH
sudo ufw allow 80/tcp   # HTTP
sudo ufw allow 443/tcp  # HTTPS


## 拒绝直接访问应用端口
sudo ufw deny 8080/tcp
sudo ufw deny 3000/tcp
sudo ufw deny 5173/tcp

数据库安全

MongoDB 启用认证

## 创建管理员用户
mongosh
use admin
db.createUser({
  user: "admin",
  pwd: "strong_password",
  roles: ["userAdminAnyDatabase"]
})


## 创建应用用户
use doracms3
db.createUser({
  user: "doracms_user",
  pwd: "strong_password",
  roles: ["readWrite"]
})

更新 .env

MONGODB_USERNAME=doracms_user
MONGODB_PASSWORD=strong_password

应用安全

## 生成强密钥
openssl rand -base64 32


## 设置文件权限
chmod 600 .env
chown www-data:www-data .env

安全配置

备份策略

数据库备份脚本

创建 backup.sh

#!/bin/bash
BACKUP_DIR="/var/backups/doracms"
DATE=$(date +%Y%m%d_%H%M%S)


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


## 备份 MongoDB
mongodump --db=doracms3 --out=$BACKUP_DIR/$DATE


## 压缩备份
cd $BACKUP_DIR
tar -czf $DATE.tar.gz $DATE
rm -rf $DATE


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


echo "Backup completed: $DATE.tar.gz"

设置定时任务:

## 编辑 crontab
crontab -e


## 每天凌晨 2 点备份
0 2 * * * /var/www/doracms/backup.sh >> /var/log/doracms-backup.log 2>&1

备份恢复

## 解压备份
tar -xzf 20241204_020000.tar.gz


## 恢复数据
mongorestore --db=doracms3 --drop 20241204_020000/doracms3

监控和维护

基础监控

## 查看应用状态
pm2 status


## 查看日志
pm2 logs --lines 100


## 查看资源使用
pm2 monit


## 重启应用
pm2 restart all

日志管理

PM2 自动日志轮转:

pm2 install pm2-logrotate
pm2 set pm2-logrotate:max_size 10M
pm2 set pm2-logrotate:retain 30

健康检查脚本

创建 health-check.sh

#!/bin/bash


## 检查服务端口
check_port() {
    if lsof -Pi :$1 -sTCP:LISTEN -t >/dev/null ; then
        echo "✓ Port $1 is running"
    else
        echo "✗ Port $1 is NOT running"
        pm2 restart all
    fi
}


check_port 8080
check_port 3000
check_port 5173

设置定时检查:

## 每 5 分钟检查一次
*/5 * * * * /var/www/doracms/health-check.sh >> /var/log/doracms-health.log 2>&1

监控面板

部署检查清单

部署前

  • [ ] 服务器配置满足要求
  • [ ] 域名已解析
  • [ ] 代码已构建(pnpm build
  • [ ] 环境变量已配置
  • [ ] 数据库已安装

部署后

  • [ ] Nginx 配置正确
  • [ ] SSL 证书有效
  • [ ] PM2 应用运行正常
  • [ ] 数据库连接成功
  • [ ] 前端页面可访问
  • [ ] 管理后台可登录
  • [ ] API 接口正常

安全检查

  • [ ] 防火墙已配置
  • [ ] 数据库已启用认证
  • [ ] 应用密钥已更新
  • [ ] 文件权限正确
  • [ ] 备份任务已设置

常见问题

应用无法启动

检查步骤

  1. 查看 PM2 日志:pm2 logs
  2. 检查端口占用:lsof -i :8080
  3. 验证环境变量:cat .env
  4. 检查依赖安装:pnpm install

SSL 证书问题

解决方案

## 更新证书
sudo certbot renew


## 重启 Nginx
sudo systemctl restart nginx

性能问题

优化建议

  1. 检查数据库索引
  2. 启用 Redis 缓存
  3. 优化 Nginx 配置
  4. 增加 PM2 实例数

数据库连接失败

解决方案

  1. 检查 MongoDB 服务:sudo systemctl status mongodb
  2. 验证连接配置:.env 文件
  3. 检查防火墙规则
  4. 查看数据库日志:/var/log/mongodb/mongod.log
以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号