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.
Zero-downtime deployment concept in 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.
const cluster = require('cluster'); if (cluster.isMaster) { cluster.fork(); } else { const app = require('./app'); app.listen(3000); }
cluster.on('exit', (worker) => { console.log(`Worker ${worker.process.pid} exited.`); cluster.fork(); });
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.
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`); }); }
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.
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.