1192805
1192805

Reputation: 1048

How to deploy different number of pm2 fork mode instances with pm2.config.js ecosystem

I'd like to run multiple pm2 instances in fork mode so that sticky sessions can be applied by nginx. Deployment is using pm2's ecosystem cfg. One way to deploy multiple fork instances in an env is to define the app multiple times with different ports:

apps : [{
  ...,
  NODE_PORT: 3000,
  env: {
    NODE_ENV: 'development',
  },
  ...,
  NODE_PORT: 3001,
  env: {
    NODE_ENV: 'development',
  },

This would seem to be ok for a single env, however support for other envs doesn't seem straightforward. Staging and production would need more fork instances and different ports.

I tried making separate ecosystem file per env, i.e. pm2.ecosystem_development.js but got error

environment is not defined in package.json file

Another thought would be to check the current env, then create an array of apps and set "apps:" in the ecosystem cfg. This may work but it'd be nice to avoid if there's a better option.

How does one go about cfging three envs with different numbers of fork instances with unique ports?

Upvotes: 1

Views: 2245

Answers (2)

fliptheweb
fliptheweb

Reputation: 1166

If you don't want to use multiple ecosystem files, you could detect the environment from process arguments.

For example, if you run your application by:

pm2 start --env staging ecosystem.config.js

ecosystem.config.js:

const DEFAULT_ENV = 'production'
const env = (() => {
  const { argv } = process
  const envArgIndex = argv.indexOf('--env')
  if (envArgIndex === -1) return
  return argv[envArgIndex + 1]
})() || DEFAULT_ENV

module.exports = {
  apps: [{
    name: "example",
    exec_mode: "cluster",
    instances: env === 'production' ? 2 : 1,
  }],
}

Upvotes: 4

1192805
1192805

Reputation: 1048

To get it working, I created an ecosystem file for each env similar to above, rather than try to cfg all envs in a single file.

Important to note: filenames must end with '.config.js', otherwise you'll see error 'environment is not defined in package.json file'.

Upvotes: 1

Related Questions