Skip to content

pm2部署服务端渲染应用

1. 安装pm2

bash
npm install -g pm2 // 如何下载失败,可临时切换镜像源执行:npm install -g pm2 --registry=https://registry.npmmirror.com,不影响全局设置

🌐 永久更换 npm 源(如果你以后一直在国内环境中开发)

bash
npm config set registry https://registry.npmmirror.com

验证是否成功:

bash
npm config get registry
# 输出应为:https://registry.npmmirror.com

之后你就可以直接安装了:

bash
npm install -g pm2

2. 启动pm2

bash
cd /opt/nginx/www/tudou-website-nuxt3
pm2 start

3. 查看pm2状态

bash
[root@tudouweb tudou-website-nuxt3]# pm2 ls
┌────┬───────────────┬─────────────┬─────────┬─────────┬──────────┬────────┬──────┬───────────┬──────────┬──────────┬──────────┬──────────┐
 id name namespace version mode pid uptime status cpu mem user watching
├────┼───────────────┼─────────────┼─────────┼─────────┼──────────┼────────┼──────┼───────────┼──────────┼──────────┼──────────┼──────────┤
 0 TD-Website default 0.4.0 cluster 3775 22m 0 online 0% 155.6mb root enabled
 1 TD-Website default 0.4.0 cluster 3782 22m 0 online 0% 131.9mb root enabled
└────┴───────────────┴─────────────┴─────────┴─────────┴──────────┴────────┴──────┴───────────┴──────────┴──────────┴──────────┴──────────┘

4. 停止pm2

bash
pm2 stop TD-Website

5. 重启pm2

bash
pm2 restart TD-Website

补充:

ecosystem.config.js文件中配置如下:

js
module.exports = {
  apps: [
    {
      name: 'TD-Website',
      script: './output/server/index.mjs',
      exec_mode: 'cluster_mode',
      instances: 2, // 启动实例数, nproc 是 CPU 核心数,执行结果是几,建议设置成几
      args: "", // 传递给脚本的参数
      watch: false, // 是否监听文件变化
      ignore_watch: ['node_modules', 'public', 'logs'], // 忽略监听的文件
      autorestart: true, // 是否自动重启
      max_memory_restart: '500M', // 最大内存重启
      error_file: './logs/app-err.log', // 错误日志
      out_file: './logs/app-out.log', // 输出日志
      merge_logs: true,
      log_date_format: 'YYYY-MM-DD HH:mm:ss',
      min_uptime: '60s',
      max_restarts: 30,
      restart_delay: 60,
      env: {
        NODE_ENV: 'production',
        HOST: '0.0.0.0'
        // ❌ 不要设置 PORT,让 PM2 自行分配端口给不同实例
      },
      env_production: {
        // 环境参数,当前指定为生产环境
        NODE_ENV: "production", //使用production模式 pm2 start ecosystem.config.js --env production
        PORT: "5050",
      },
      env_test: {
        // 环境参数,当前为测试环境
        NODE_ENV: "test",
      }
    }
  ]
}

Released under the MIT License.