PM2 (Node.js) not listening on specific port for Expressjs app/api

I spent good amount of time last week to figure out how to make Expressjs app to listen on a specific port (say, 3005) for one of the projects. Regular PM2 setup involves creating a new config block in the ecosystem file.

{
    "apps": [
        {
            "name": "api",
            "script": "/var/www/api/app.js",
            "ignore_watch": ["frontend/", ".*"],
            "log_date_format": "YYYY-MM-DD HH:mm",
            "env": {
                "NODE_ENV": "production",
                "PORT": "3001"
            }
        }
   ]
}

This works for regular nodejs app, however, if your APIs are using expressjs framework, its a bit different. All you need to change is, instead of app.js as the start script, you have to use bin/www in ecosystem config. So, the updated config looks like this:

{
    "apps": [
        {
            "name": "api",
            "script": "/var/www/api/bin/www",
            "ignore_watch": ["frontend/", ".*"],
            "log_date_format": "YYYY-MM-DD HH:mm",
            "env": {
                "NODE_ENV": "production",
                "PORT": "3005"
            }
        }
   ]
}

And this will work like a charm!

Leave a Reply

Your email address will not be published. Required fields are marked *