如何使用pm2使express.js在端口(8080)上仅运行一个实例,而在第二实例上使用另一个端口(8081)

时间:2019-01-03 07:29:33

标签: node.js express pm2

我到处搜索,但找不到答案 有关如何使用Express.js配置pm2 这是到目前为止我根据其他人的答案和pm2文档获得的信息。

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

常量端口= process.env.NODE_PORT;

除非使用||,否则我将无法定义。 8080。

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

我现在需要它仅在dev env上工作。.

,但似乎无法获得我在ecosystem.config.js文件上配置的内容。 并在我的ecosystem.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'
    }
  }
  };

1 个答案:

答案 0 :(得分:0)

我正在使用环境变量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;
相关问题