【问题标题】:How to make express.js using pm2 run only one instance on port (8080) and on second instance use another port (8081)如何使用 pm2 使 express.js 在端口(8080)上仅运行一个实例,而在第二个实例上使用另一个端口(8081)
【发布时间】:2019-01-03 17:41:11
【问题描述】:

我找遍了,但找不到答案 如何使用 Express.js 配置 pm2 这是我迄今为止根据其他人的答案和 pm2 文档得出的结果。

这是在服务器主文件(index.js)上:

常量端口 = process.env.NODE_PORT;

除非我使用 ||,否则我会得到未定义8080 .

常量端口 = process.env.NODE_PORT || 8080;

我现在只需要它在开发环境上工作..

但它似乎没有得到我在生态系统.config.js 文件上配置的内容。 在我的生态系统.config.js 上:

module.exports = {
  apps: [{
      name: 'API',
      script: 'index.js',

  // Options reference: https://pm2.io/doc/en/runtime/reference/ecosystem-file/
  args: 'one two',
  instances: 1,
  exec_mode: "fork_mode",
  autorestart: true,
  watch: false,
  max_memory_restart: '1G',
  env: {
    NODE_PORT = 8080 `pm2 start app.js -f`,
    NODE_PORT = 8081 `pm2 start app.js -f`,
    NODE_ENV: 'development'
  },
  env_production: {
    NODE_ENV: 'production'
  }
},
{
  name: 'API',
  script: 'index.js',

  // Options reference: https://pm2.io/doc/en/runtime/reference/ecosystem-file/
  args: 'one two',
  instances: 1,
  exec_mode: "fork_mode",
  autorestart: true,
  watch: false,
  max_memory_restart: '1G',
  env: {
    PORT: 8081,
    NODE_ENV: 'development'
  },
  env_production: {
    NODE_ENV: 'production'
  }
}
  ],

  deploy: {
production: {
  user: 'node',
  host: '212.83.163.1',
  ref: 'origin/master',
  repo: 'git@github.com:repo.git',
  path: '/var/www/production',
  'post-deploy': 'npm install && pm2 reload ecosystem.config.js --env 
production'
    }
  }
  };

【问题讨论】:

    标签: node.js express pm2


    【解决方案1】:

    我正在使用环境变量 process.env.NODE_APP_INSTANCE 来执行此操作。 (https://pm2.io/doc/en/runtime/guide/load-balancing/#cluster-environment-variable)

    我在启动服务器之前设置我的PORT,然后我根据PORT 环境变量和NODE_APP_INSTANCE 设置服务器端口,如下所示:

    const nodeInstance = parseInt(process.env.NODE_APP_INSTANCE || 0, 10);
    const port = process.env.PORT + nodeInstance;
    

    【讨论】:

      猜你喜欢
      • 2014-11-23
      • 1970-01-01
      • 2018-09-02
      • 1970-01-01
      • 2020-08-22
      • 2016-10-18
      • 2017-06-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多