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.
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.
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.
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 127.0.0.1:8090;
server 127.0.0.1:8091;
}
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.
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.
This ip_hash is required for other application servers if an HTTP session is maintained.