How to use Nginx In NodeJS

If your system has more than one application server to respond to, and you need to distribute client requests across all servers then you can smartly use Nginx as a proxy server. Nginx sits on the front of your server pool and distributes requests using some intelligent fashion. In the following example, we have 4 instances of the same NodeJS application on different ports, also you can use another server.

Example: Implementation to show load balancing servers by using nginx.

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

// API endpoint
app.get('/', (req,res)=>{
    res.send("Welcome to w3wiki !");
})

// Launching application on several ports
app.listen(3000);
app.listen(3001);
app.listen(3002);
app.listen(3003);

Now install Nginx on your machine and create a new file in /etc/nginx/conf.d/ called your-domain.com.conf with the following code in it. 

upstream my_http_servers {
# httpServer1 listens to port 3000
server 127.0.0.1:3000;

# httpServer2 listens to port 3001
server 127.0.0.1:3001;

# httpServer3 listens to port 3002
server 127.0.0.1:3002;

# httpServer4 listens to port 3003
server 127.0.0.1:3003;
}
server {
listen 80;
server_name your-domain.com www.your-domain.com;
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $http_host;
proxy_pass http://my_http_servers;
}
}

How to Create Load Balancing Servers using Node.js ?

In node, Load balancing is a technique used to distribute incoming network traffic across multiple servers to ensure no single server becomes overwhelmed, thus improving responsiveness and availability. In this article, we’ll explore how to create a load-balancing server using Node.js.

Similar Reads

Why Load Balancing?

Load balancing is essential for:...

Using Cluster Module

NodeJS has a built-in module called Cluster Module to take advantage of a multi-core system. Using this module you can launch NodeJS instances to each core of your system. Master process listening on a port to accept client requests and distribute across the workers using some intelligent fashion. So, using this module you can utilize the working ability of your system. The following example covers the performance difference by using and without using the Cluster Module....

Using Nginx

If your system has more than one application server to respond to, and you need to distribute client requests across all servers then you can smartly use Nginx as a proxy server. Nginx sits on the front of your server pool and distributes requests using some intelligent fashion. In the following example, we have 4 instances of the same NodeJS application on different ports, also you can use another server....

Using Express Web Server

There is a lot of advantage to an Express web server. If you are comfortable with NodeJS, you can implement your own Express base load balancer as shown in the following example....