Mar 5, 2021· 3 mins to read

Scaling your Nodejs application with Zero Downtime deployment


Scaling your Nodejs application with Zero Downtime deployment

What do you do when your customers faces a bad experience whenever you deploy a fix or features in production server?

Well, your server may take few seconds to restart. but, it can badly impact your business and chances of losing your potential customers. As a developer, it is our responsibility to make sure that the application has high availability.

This article is going to explain about how you can scale your Nodejs application with Zero downtime deployment.

Let’s look into a scenario where the application faces the downtime whenever we deploy a change in the server.

Before Zero downtime

Here we have a simple nodejs application server with pm2 configuration to deploy it in the digital ocean.

module.exports = {
  apps: [
    {
      name: "app",
      script: "./app.js",
      env: {
        NODE_ENV: "development",
      },
      env_production: {
        NODE_ENV: "production",
      },
    },
  ],
};

We can deploy the application using the command,

pm2 start pm2.config.js

Problem with this approach is, whenever we restart the pm2 process manager. it will shut down the entire application and restart it. It can cause the downtime for our application.

Solution

To address this problem, we need to use PM2 Cluster mode. PM2 will use fork mode by default. we need to specify in PM2 configuration to deploy them in a cluster mode.

Let’s change the pm2 config to use cluster mode,

module.exports = {
    apps : [{
      name: "app",
      script: "./app.js",
      instances : 4,
      exec_mode : "cluster",
      env: {
        NODE_ENV: "development",
      },
      env_production: {
        NODE_ENV: "production",
      }
    }]
  }

Here, we have added instances and exec_mode. exec-mode defines the mode that we want to deploy our application. instanced defines the number of instances that we want to run inside the cluster.

Once we are done with configuration changes, we can deploy our application using the command.

pm2 start pm2.config.js

An important thing to note here is, we were using pm2 restart whenever we deploy a change or features. but now, we need use pm2 reload < app name | id > to deploy them in the cluster mode.

pm2 reload < app name | id >

After this small change in the deployment configuration. you can see a change in the application downtime. Here’s a working example for it.

After Zero downtime configuration

Copyright © Cloudnweb. All rights reserved.