aris
aris

Reputation: 597

How to make express.js using pm2 run only one instance on port (8080) and on second instance use another port (8081)

I searched all over, but could not find the answer for how to config pm2 with Express.js here is what i have so far based on other's answers and pm2 documentation.

this is on the server main file(index.js):

const port = process.env.NODE_PORT;

I get undefined unless i use || 8080 .

const port = process.env.NODE_PORT || 8080;

I need it working only on dev env for now..

but it seems it does not get what i config on ecosystem.config.js file. and on my 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: '[email protected]:repo.git',
  path: '/var/www/production',
  'post-deploy': 'npm install && pm2 reload ecosystem.config.js --env 
production'
    }
  }
  };

Upvotes: 0

Views: 1169

Answers (1)

Łukasz Szewczak
Łukasz Szewczak

Reputation: 1881

I'm using environment variable process.env.NODE_APP_INSTANCE to do this. (https://pm2.io/doc/en/runtime/guide/load-balancing/#cluster-environment-variable)

I'm setting my PORT before starting my server, and then I'm setting server port based on PORT environment variable and NODE_APP_INSTANCE, something like this:

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

Upvotes: 0

Related Questions