0

I have a node application runs a node JS server on port 1407 (hardcoded in server.js - using express) and also runs two react applications on port 3000 and port 3001. I am using concurrently to be able to run multiple npm commands from one npm script.

I need to be able to deploy the application to multiple domains on the server, where each domain will need three ports. however the ports are hardcoded in the package.json and in server.js as to what port they should be deployed on.

We'll be using the same git repostory to handle all domains / applications.

I'm looking at using PM2 to manage the node processes but I am unsure how I can set up the application for multiple ports for each domain and make the ports dynamic.

I also have hardcoded links within the react applications to the API endpoints from the node server which reference the :1407 port.

My package.js scripts:

"scripts": {
  "server": "node server.js",
  "server-dev": "nodemon server.js",
  "fos": "cd fos && export PORT=3000; npx serve -s www",
  "fos-dev": "cd fos && export PORT=3000; npm start",
  "master": "cd master && export PORT=3001; npx serve -s www",
  "master-dev": "cd master && export PORT=3001; npm start",
  "hcl": "concurrently \"npm run server\" \"npm run master\" \"npm run fos\"",
  "hcl-dev": "concurrently \"npm run server-dev\" \"npm run master-dev\" \"npm run fos-dev\"",
  "hcl-build": "cd fos && npm run build && cd ../master && npm run build",
  "hcl-install": "npm i && cd fos && npm i && cd ../master && npm i"
},

Any help would be appreciated.

lky
  • 1,081
  • 3
  • 15
  • 31

1 Answers1

1

Using PM2, you have 2 ways for starting you process. First by using the command line, like this:

PORT=3008 pm2 start -name "My process" /path/to/my/process

this command will start your process at port 3008 for example.

This work if you fix the port something like this in your server source code:

var port  = process.env.PORT || '3509';

So if you don't specify PORT in your PM2 starting commande, it will use the 3509 port.

Second way is to generate a PM2 ecosystem file like this:

pm2 init simple

and then edit the file for setting what you need, for example:

module.exports = {
  apps : [
  {
    name      : "My process",
    script    : "/path/to/my/process",
    env: {
      NODE_ENV: "production",
      PORT: 3509    
    }
  }]
}

And then start the process like this:

pm2 start ecosystem.config.js

More information about ecosystem parameters here: https://pm2.keymetrics.io/docs/usage/application-declaration/

You can specify many process in an ecosystem file.

Alaindeseine
  • 3,260
  • 1
  • 11
  • 21