PM2入门指北

249 阅读1分钟

全局安装:

npm install pm2@latest -g

常用命令

启动:pm2 start ...

列出应用程序:pm2 list

重启:pm2 restart /

停止:pm2 stop /

删除:pm2 delete /

日志:pm2 logs /

使用 CLI 面板查看日志:pm2 monit /

查看版本:pm2 --version

进程守护

node app.js 和 nodemon app.js,进程崩溃则不能访问。pm2 遇到进程崩溃,会自动重启。

启动 package.json 中的 script

pm2 start --name [project name] npm -- run [script name]
例: pm2 start --name demo npm --run dev

用 PM2 配生产环境变量

在项目根目录生成配置文件:

pm2 init simple

这将生成一个 ecosystem.config.js 配置文件

ecosystem.config.js:

module.exports = {
  apps: [
    {
      name: 'card-server',
      cwd: '/var/www/card-server', // 改成你的项目绝对路径
      script: './app.js', // 改成你的实际入口:app.js / server.js / bin/www / dist/index.js
      interpreter: 'node',

      // 让 Node 启动时读取 .env.production
      node_args: '--env-file=.env.production',

      // 单实例先最稳;后面要吃多核再改成 cluster
      instances: 1,
      exec_mode: 'fork',

      // 常用生产配置
      autorestart: true,
      watch: false,
      max_memory_restart: '300M',
      time: true,

      // 日志文件
      error_file: '/var/log/card-server/error.log',
      out_file: '/var/log/card-server/out.log',
      log_date_format: 'YYYY-MM-DD HH:mm:ss Z',
      merge_logs: true,

      // 默认环境
      env: {
        NODE_ENV: 'development',
        TZ: 'Asia/Shanghai',
      },

      // 生产环境
      env_production: {
        NODE_ENV: 'production',
        TZ: 'Asia/Shanghai',
      },
    },
  ],
}

.env.production

NODE_ENV=production
PORT=3000

# MongoDB
MONGODB_URI=mongodb://127.0.0.1:27017/card
MONGODB_DB_NAME=card

# 鉴权/加密
JWT_SECRET=replace_with_a_long_random_string
JWT_EXPIRES_IN=7d
COOKIE_SECRET=replace_with_another_long_random_string

# 前端域名 / CORS
APP_URL=https://yourdomain.com
FRONTEND_URL=https://yourdomain.com
CORS_ORIGIN=https://yourdomain.com

# 运行环境
TZ=Asia/Shanghai

# 可选
LOG_LEVEL=info

启动:

pm2 start ecosystem.config.js --env production

如果你改了环境变量,记得重启并更新环境:

pm2 restart myapp --update-env

官网:

https://pm2.keymetrics.io

中文官网:

https://pm2.fenxianglu.cn