Home   express  

How to set up load balancers for an Express.js web application

Setting up load balancers for an Express.js application involves distributing incoming requests across multiple instances of your application to ensure high availability, reliability, and scalability. Here’s a step-by-step guide on how to set up load balancers using various methods and tools:


Step 1: Prepare Your Express Application

First, ensure your Express application is set up and running. Here’s a basic example (app.js):

const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.send('Hello, World!');

const port = process.env.PORT || 3000;
app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);

Step 2: Run Multiple Instances

To effectively load balance, you need to run multiple instances of your application. This can be done in several ways:

Using Node.js Clustering

Node.js has a built-in cluster module to utilize multiple CPU cores:

const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;
const app = require('./app'); // Import your Express app

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

  cluster.on('exit', (worker, code, signal) => {
    console.log(`Worker ${worker.process.pid} died`);
} else {
  app.listen(3000, () => {
    console.log(`Worker ${process.pid} started`);

Using Docker

You can containerize your application and run multiple containers:

  1. Create a Dockerfile:

    FROM node:14
    WORKDIR /app
    COPY package*.json ./
    RUN npm install
    COPY . .
    EXPOSE 3000
    CMD ["node", "app.js"]
  2. Build and Run Docker Containers:

    docker build -t myexpressapp .
    docker run -d -p 3001:3000 myexpressapp
    docker run -d -p 3002:3000 myexpressapp
    docker run -d -p 3003:3000 myexpressapp

Step 3: Set Up Load Balancing

Using Nginx

Nginx is a popular web server and load balancer. Here’s how to set it up:

  1. Install Nginx (on Ubuntu):

    sudo apt update
    sudo apt install nginx
  2. Configure Nginx:

    Open the Nginx configuration file (usually located at /etc/nginx/sites-available/default) and set up the load balancing configuration:

    upstream myexpressapp {
    server {
        listen 80;
        location / {
            proxy_pass http://myexpressapp;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
  3. Restart Nginx:

    sudo systemctl restart nginx

Using HAProxy

HAProxy is another popular load balancer. Here’s how to set it up:

  1. Install HAProxy (on Ubuntu):

    sudo apt update
    sudo apt install haproxy
  2. Configure HAProxy:

    Open the HAProxy configuration file (/etc/haproxy/haproxy.cfg) and set up the load balancing configuration:

        log /dev/log local0
        log /dev/log local1 notice
        chroot /var/lib/haproxy
        stats socket /run/haproxy/admin.sock mode 660 level admin
        stats timeout 30s
        user haproxy
        group haproxy
        log     global
        option  httplog
        option  dontlognull
        timeout connect 5000
        timeout client  50000
        timeout server  50000
    frontend http_front
        bind *:80
        default_backend http_back
    backend http_back
        balance roundrobin
        server server1 check
        server server2 check
        server server3 check
  3. Restart HAProxy:

    sudo systemctl restart haproxy

Step 4: Cloud-Based Load Balancers

AWS Elastic Load Balancer (ELB)

  1. Set Up EC2 Instances:

    • Launch multiple EC2 instances running your Express app.
  2. Create an ELB:

    • Go to the AWS Management Console.
    • Navigate to the EC2 Dashboard and select "Load Balancers".
    • Create a new load balancer, configure the listeners, and register your EC2 instances.
  3. Configure Health Checks:

    • Set up health checks to monitor the status of your instances.

Google Cloud Load Balancer

  1. Set Up Compute Engine Instances:

    • Launch multiple instances on Google Compute Engine.
  2. Create an HTTP(S) Load Balancer:

    • Go to the Google Cloud Console.
    • Navigate to "Load balancing" and create a new HTTP(S) load balancer.
    • Configure the backend service and add your instances.
  3. Set Up Health Checks:

    • Configure health checks for your backend service.
Published on: Jul 08, 2024, 09:03 PM  


Add your comment