mirror of
http://git.nowherejezfoltodf4jiyl6r56jnzintap5vyjlia7fkirfsnfizflqd.onion/nihilist/selfhosting-blogposts.git
synced 2025-05-17 04:36:58 +00:00
103 lines
2.3 KiB
Markdown
103 lines
2.3 KiB
Markdown
# NGINX Load Balancing
|
|
|
|
First off you will need a debian10 server to run nginx as a load balancer, and 2 other http servers.
|
|
|
|
## **Initial Setup**
|
|
|
|
First we're go install nginx:
|
|
|
|
|
|
apt update -y && apt upgrade -y
|
|
apt install nginx -y
|
|
|
|
|
|
|
|
Then you will need 2 http servers (mine are 192.168.0.150:80 and 192.168.0.151:80):
|
|
|
|

|
|
|
|
Then make the configuration to load balance the 2 servers:
|
|
|
|
|
|
nano /etc/nginx/sites-available/loadb.conf
|
|
|
|
|
|
|
|
|
|
upstream backend {
|
|
server 192.168.0.150:80 weight=1;
|
|
server 192.168.0.151:80 weight=2;
|
|
|
|
}
|
|
server {
|
|
listen 80;
|
|
listen [::]:80;
|
|
location / {
|
|
proxy_pass http://backend;
|
|
}
|
|
}
|
|
|
|
|
|
Hit CTRL+S to save and CTRL+X to exit nano.
|
|
|
|
## **Launching the config**
|
|
|
|
Now remove the default config and launch reload nginx:
|
|
|
|
|
|
|
|
rm /etc/nginx/sites-available/default
|
|
rm /etc/nginx/sites-enabled/default
|
|
|
|
ln -s /etc/nginx/sites-available/loadb.conf /etc/nginx/sites-enabled/loadb.conf
|
|
nginx -s reload
|
|
|
|
|
|
|
|

|
|
|
|
And test if it load balances well. It should give us the output of the .151 server because it has the highest weight:
|
|
|
|

|
|
|
|
As you can see, nginx determines the number of allowed requests to each load balanced website with the weight parameter, for instance, our .151 server has a weight of 2, so nginx will allow us 2 requests before switching back to the .150 server.
|
|
|
|
This is also possible with other ports like database servers:
|
|
|
|
|
|
upstream sqlbackend {
|
|
server 192.168.0.150:3386 weight=1;
|
|
server 192.168.0.151:3386 weight=2;
|
|
|
|
}
|
|
server {
|
|
listen 3386;
|
|
listen [::]:3386;
|
|
location / {
|
|
proxy_pass sqlbackend;
|
|
}
|
|
}
|
|
|
|
|
|
|
|
It is also possible to do with UDP:
|
|
|
|
|
|
stream {
|
|
upstream ntp {
|
|
server 192.168.0.150:123 weight=2;
|
|
server 192.168.0.151:123 weight=3;
|
|
|
|
}
|
|
server {
|
|
listen 123 udp;
|
|
listen [::]:123 udp;
|
|
location / {
|
|
proxy_pass ntp;
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
Here you can see how flexible nginx truly is, it can handle load balancing of multiple types of services, apply weights parameters over tcp/udp services.
|
|
|