0
0
Expressframework~5 mins

Zero-downtime deployment concept in Express

Choose your learning style9 modes available
Introduction

Zero-downtime deployment means updating your app without making users wait or see errors. It keeps the app working smoothly while you add new features or fix bugs.

When you want to update your Express app without stopping it.
When users must always access your app without interruptions.
When you deploy bug fixes or new features often.
When you run a website or API that needs to be available 24/7.
Syntax
Express
const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
  for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  cluster.on('exit', (worker, code, signal) => {
    console.log(`Worker ${worker.process.pid} died. Starting a new one.`);
    cluster.fork();
  });
} else {
  const app = require('./app');
  app.listen(3000);
}

This example uses Node.js cluster to run multiple app instances.

When a worker stops, the master starts a new one to keep the app running.

Examples
Simple cluster setup with one worker process.
Express
const cluster = require('cluster');

if (cluster.isMaster) {
  cluster.fork();
} else {
  const app = require('./app');
  app.listen(3000);
}
Restart worker automatically when it exits to avoid downtime.
Express
cluster.on('exit', (worker) => {
  console.log(`Worker ${worker.process.pid} exited.`);
  cluster.fork();
});
Sample Program

This program uses Node.js cluster to run multiple Express workers. If a worker stops, the master starts a new one. This keeps the app available without downtime during updates or crashes.

Express
const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
  console.log(`Master ${process.pid} is running`);

  for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  cluster.on('exit', (worker, code, signal) => {
    console.log(`Worker ${worker.process.pid} died. Starting a new one.`);
    cluster.fork();
  });
} else {
  const express = require('express');
  const app = express();

  app.get('/', (req, res) => {
    res.send(`Hello from worker ${process.pid}`);
  });

  app.listen(3000, () => {
    console.log(`Worker ${process.pid} started`);
  });
}
OutputSuccess
Important Notes

Zero-downtime deployment often uses multiple processes or servers to avoid stopping the app.

Using a process manager like PM2 can simplify zero-downtime deployment.

Always test your deployment process to ensure users don't see errors or downtime.

Summary

Zero-downtime deployment keeps your app running while updating.

Node.js cluster helps run multiple app instances for this purpose.

Restarting workers automatically avoids downtime if one crashes.