tamak
tamak

Reputation: 1591

How do I reference the process PORT assignment for PM2 in my child script / process?

I am experimenting with PM2 for my node.js environment on Ubunty and want to try to figure out how I can take a port number specified in the command line like the following...

$pm2 start test.js --node-args "port=3001 sitename='first pm2 app'"

... and then in my target script (test.js in the above example) and use that port number for my .listen port... for example:

    var express = require('express')
    var app = express()

    app.get('/', function (req, res) {
      res.send('Hello World!')
    })

    app.listen(PORT_NUM_HERE, function () {
      console.log('Example app listening on port ' + PORT_NUM_HERE + '!')
    })

I also see that with PM2 I can use a configuration file to define process name, port, etc. and if I do that, same question, how to take the port used in the configuration file and use it in my child script.

example configuration file:

{
  "apps": [
    {
      "name": "futurestudio-homepage",
      "script": "./homepage/server.js",
      "instances": 2,
      "exec_mode": "cluster",
      "env": {
        "NODE_ENV": "production",
        "PORT": "3000",
      }
    }
}

] }

Upvotes: 2

Views: 3976

Answers (1)

sr9yar
sr9yar

Reputation: 5310

Specify environmental variable on the command line:

NODE_PORT=3100 pm2 start ./src/server.ts --name dev

PM2 can be configured by using process.json or ecosystem.config.js. The docs are here.

This should start your app on port 3100:

pm2 start ecosystem.config.js

Contents of the ecosystem.config.js file:

// ecosystem.config.js
module.exports = {
  apps : [{
    name: "dev",
    script: "src/server.ts",
    cwd: "/root/api",
    env: {
        NODE_PORT:"3100",
        NODE_ENV:"development"
    }
  }]
}

Add you can test it by running something like this on your server:

curl http://127.0.0.1:3100

Upvotes: 1

Related Questions