使用 pm2 部署前端项目

22 min read

pm2 配置文件

在项目根目录下新建 ecosystem.config.js

module.exports = {
  apps: [{
    name: "app",
    script: "app.js"
  }],
  deploy: {
    // "production" 是环境名称
    production: {
      // SSH key 路径
      key: `${process.env.HOME}/.ssh/your-privite.key`,
      // SSH 用户
      user: "www",
      // SSH 端口
      host: ["your.remote.server"],
      // SSH 配置
      ssh_options: "StrictHostKeyChecking=no",
      // GIT 远程分支
      ref: "origin/master",
      // GIT 仓库
      repo: "[email protected]:username/repository.git",
      // 服务器部署路径
      path: "/var/www/my-repository",
      // 安装后置任务
      'post-setup': "npm install",
      // 部署后置任务
      'post-deploy': "npm run build",
    },
  }
}

由于 pm2 是用来部署 node 代码的,需要提供一个 js 文件用来执行,上面配置文件制定了项目根目录下的 app.js

里面写一行 log 即可

console.log('app is running')

首次部署配置

$ pm2 deploy production setup

从上面配置文件可知,setup 完成后会执行 npm install

首次部署后 pm2 会在执行文件夹(配置文件中的path) 生成三个文件夹

  • current - 当前版本代码,可以配置为 nginx 指向,也是 git repo
  • shared - 里面有log 和pid 等信息
  • source - git 拉下来的代码

一些部署命令

# 首次部署命令
pm2 deploy production setup

# 非首次部署命令
pm2 deploy production update

# 回退一个版本
pm2 deploy production revert 1

# 远程执行服务器命令
pm2 deploy production exec "pm2 reload all"