Skip to content

Deploy Node application with multiple environments using PM2

What's PM2?

PM2 is a process manager for node js applications that allows you to run multiple instances of a project. Instead of having just one application listening for incoming requests you will have multiple. This allows you to have 0 downtime because if one instance fails or encounters and error the other ones can handle the remaining traffic. PM2 also includes a load balancer, so you don't need to configure this yourself.

The problem deploying an application using PM2

When trying to deploy an application with multiple env like development and staging using PM2 it can be tricky, specially specifying which command to use on the package.json in order to initialize the app using PM2 when deploying the app.

Solution

First we are going to add or change our ecosystem.config.js to be able to initialize our PM2 app on different environments deppending on the process.env.NODE_ENV variable passed, we will also specify the script used to run the application

module.exports = {
  apps: [
    {
      // Name of the app
      name: 'mynewapp',
      // Script use to initialize app in this case just run app.js
      script: './app.js',
      // Number of instances
      instances: 'max',
      // Execution mode used to run app
      exec_mode : "cluster",
      // You can specify more env variables if you need to or use a package like dotenv
      // Development environment
      env: {
        NODE_ENV: 'development'
      },
      // Integration environment
      env_integration: {
        NODE_ENV: 'integration'
      },
      // Production environment
      env_production: {
        NODE_ENV: 'production'
      }
    },
  ]
};

Now we will add a new script to our package.json file in order to initialize our app using PM2, when deploying you application specify npm run start as the command to run your application, dont forget to set the NODE_ENV environment variable to your desire value on the platform you are using for deployment or create multiple scripts with defined env for example "start-prod": export NODE_ENV=production && pm2 start ecosystem.config.js

{

  "scripts": {
    "build": "tsc",
    "start": "node_modules/pm2/bin/pm2-runtime start ecosystem.config.js",
  },
}