How to deploy Node.js app with PM2 in production

To deploy Node.js app with PM2 it’s very simple and nowadays is very important to use the right tool which facilitate your time. Time is the most valuable resource that a human being can own, so try to avoid those tools which are time-consuming.

I would like to present below a simple solution found by me to deploy Node.js app with PM2. I needed a fast solution and with less configuration as possible. I tried as well Forever JS, you can find the NPM page here or Github repository. But I prefer the documentation and explanation of [PM2](https://pm2.keymetrics.io/).

Firstly you need to create a pm2.json file and put it preferably in the root of your project:

{
    "apps": [
        {
            "name": "web",
            "exec_mode": "cluster",
            "instances": "max",
            "script": "./lib/server.ts",
            "interpreter": "ts-node",
            "env": {
                "ENV": "prod",
                "PORT": 3000,
                "DB_USERNAME": "boobo94_username",
                "DB_PASSWORD": "123",
                "DB_NAME": "some_db_name",
                "DB_HOST": "127.0.0.1",
                "DB_DIALECT": "postgres",
                "DB_PORT": 5432,
                "SECRET_KEY": "boobo94_is_my_secret_key",
            }
        }
    ]
}

Prerequested

  • npm & node
  • PM2 npm i -g pm2
  • Typescript npm install -g typescript
  • PostgreSQL installed

How to run it

  1. pm2 install typescript
  2. pm2 install @types/node
  3. pm2 start pm2.json

The name of web service is web under pm2 manager.

That’s all. To check the availability:

pm2 show web

My example use typescript, if you don’t want typescript, in the pm2.json file the value of interpreter would be node and from How to run it section you can skip the first two steps.

Leave a Reply

Your email address will not be published.