In this article we will see, Nginx for Front-end Developers - Load Balancers. this is a Part three of Nginx for Front-end Developers. To read the Previous articles
Above all , Load balancers are an important feature in Nginx. we will see how to configure it in this article.
Load Balancing is nothing but distributing the traffic to different servers.
Mainly, there are three mechanism with which the nginx distributes the request to the speicifed server.
1upstream backend {2 # no load balancing method is specified for Round Robin3 server backend1.example.com;4 server backend2.example.com;5}
1upstream backend {2 least_conn;3 server backend1.example.com;4 server backend2.example.com;5}
1upstream backend {2 ip_hash;3 server backend1.example.com;4 server backend2.example.com;5}
upstream is the keyword used to specify the load balancer in nginx configuration.
we are going to load balance the request to three different servers using the nginx load balancer.
Further, create a three simple node server with different ports and run the server.
First Server - app.js
1const express = require("express")23const app = express()45app.get("/", (req, res) => {6 res.send("Welcome to Server 1")7})89app.listen(3000, () => {10 console.log("app is listening to port 3000")11})
Second Server - app.js
1const express = require("express")23const app = express()45app.get("/", (req, res) => {6 res.send("Welcome to server 3")7})89app.listen(3001, () => {10 console.log("app is listening to port 3002")11})
Third Server - app.js
1const express = require("express")23const app = express()45app.get("/", (req, res) => {6 res.send("app is running in server 2")7})89app.listen(3002, () => {10 console.log("app is listening to port 3001")11})
Meanwhile , Run all the servers with the following command
1$ node app.js
Now, servers are running. After that, you need to configure nginx to load balance between these severs.
I assume that you have already installed nginx and configured it before. if you are not, please follow this article before continuing.
create a file called node-app in the /etc/nginx/sites-available.
(Note : I am using Ubuntu , the nginx file location is different for other operating systems)
1upstream backend {23 server 127.0.0.1:3000;45 server 127.0.0.1:3001;67 server 127.0.0.1:3002;89 }1011server {1213 listen 80;1415 server_name localhost;1617 location / {1819 proxy_pass "http://backend";2021 }22}
there are two directive that you need to note.
After that, you need to move the file from sites-available to sites-enabled
1$ sudo ln -s /etc/nginx/sites-available/node-app /etc/nginx/sites-enabled
Similarly , restart the nginx service
1$ sudo service nginx restart
Once the nginx service resstarted successfully. visit the http://localhost in the browser
In conclusion , that's how the nginx load balance between different servers.
To sum up, this article series covered Nginx Setup , Basic Configuration and Nginx Load Balancer
Reference :
No spam, ever. Unsubscribe anytime.