How to specify a port number for pm2

You can use an environment variable. For example:

  1. NODE_PORT=3002 pm2 start -i 0 app.js

  2. Here is how to read the value in app:

console.log(process.env.NODE_PORT);

Or, if you are building an Express app:

  1. PORT=3002 pm2 start -i 0 ./bin/www

  2. Express loads PORT automatically when the application starts.


You need to use -- to tell pm2 to stop parsing his options and give the rest to the program, then when you spawn direct binary, you need to tell pm2 that you don't want to use nodejs, so :

pm2 start rethinkdb --interpreter none -- --port 8082

You see you need -- --port 8082


An easy way of telling your server application on which port to run is through PM2's

ecosystem configuration files

in conjunction with properly configured use of $PORT environment vars inside your server application. That means your server reads $PORT environment var to start the server or microservice on specified port.

There are different formats available you can choose for the file to have. I personally use the CommonJS module format (amongst other options are JSON and YAML).

Inside ecosystem.config.js you specify one entry object for each server instance you want to launch through PM2.

The point is that you can also specify environment vars for the different processes and that way you can setup $PORT for all the processes. The following is an example config for three different processes.

    module.exports = {
  apps : [
  {
    name      : "Main API server",
    script    : "./backend/dist/main.js",
    instances : "2",
    exec_mode : "cluster",
    env: {
      NODE_ENV: "production",
      PORT: 4300    
    }
  },
  {
    name      : "Worker server 1",
    script    : "./backend-worker/dist/main.js",
    instances : "1",
    exec_mode : "fork",
    env: {
      NODE_ENV: "production",
      PORT: 4000,
    },
    
  },
  {
    name      : "Worker server 2",
    script    : "./backend-worker/dist/main.js",
    instances : "1",
    exec_mode : "fork",
    env: {
      NODE_ENV: "production",
      PORT: 4001,
    }
  },
  ]
}

One note: This configuration uses PM2 as a loadbalancer for the first process that runs as cluster on two cores. The other (worker-)processes are run each on is on process on the specified port.

An example snippet of server startup code using the environment $PORT var for a NodeJS server is following:

// ...
const port = (process.env.PORT) ? process.env.PORT : 4300

console.log('$PORT: ', port)
const server = await app.listen(port, '0.0.0.0')
// ...

When you have all in place you simply call following to startup your servers:

pm2 start ecosystem.config.js