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: {
PORT: 4000,
},
},
{
name : "Worker server 2",
script : "./backend-worker/dist/main.js",
instances : "1",
exec_mode : "fork",
env: {
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 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