Home > References > Hosting > Server configuration setup

Load balancing a webapp in NGINX

Last updated : 30 April 2022

1. Overview

This article explains how to load balance a web app in NGINX. The web app can be any application running in a specified port. Preferably multiple instances to make sense of load balancing.

Nginx load balancing
Figure 1 : Nginx load balancing

2. Setup

2.1 Create a conf file

Locate the Nginx configuration directory. Usually, this is located in /etc/nginx. Create a conf file to include the load balancing code. For this example, let it be mysite.com.conf. Your file needs to have the conf extension. That is how Nginx knows how to pick configuration files at startup time.

2.2 Configure load-balancing

The upstream forwards the HTTP requests to the specified cluster of servers within the upstream block. That means the user requests reaching your site are forwarded to servers running on ports 3000 and 3001.

upstream webserver {

2.3 Forwarding requests to load balancer

Below is the complete configuration file you need to load-balance your website. You can increase the number of upstream servers depending on your traffic.

upstream webserver {
server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name mysite.com www.mysite.com;
    ssl_certificate #path/to/ssl/ssl.cer;
    ssl_certificate_key #/path/to/ssl.key;
     location / {
        proxy_pass http://webserver;

If you have a separate server block that listens to port 80, make sure to do a 301 redirect appropriately. The default port 80 is not included in the code.

3. Load balancing single-page apps

If you are load balancing a single page application built with Reactjs or Nextjs, your upstream needs an IP hash. The ip_hash binds users' IP addresses to the same server to maintain sticky sessions. That avoids page refreshes in your single-page application.

upstream webserver {

This ip_hash is required for other application servers if an HTTP session is maintained.

By: Lance
Lance is a software engineer with over 15 years of experience in full-stack software development.

Comments are disabled

No Comments