Nginx implements cluster load balancing configuration process resolution

  • 2020-05-13 04:29:30
  • OfStack

The load balancing function of Nginx is actually the same function as the agent of nginx, only the agent 1 machine is changed to multiple machines. Compared with lvs, nginx is a more advanced application layer. It does not involve the modification of ip and the kernel, but simply forwards the user's request to the subsequent machine. This means that the back-end RS does not need to be configured with a public network.

1. Experimental environment

Nginx scheduler (public 172.16.254.200 privite 192.168.0.48)
RS1 only Intranet IP (192.168.0.18)
RS2 extranet IP only (192.168.0.28)

2. Configuration files

Edit the configuration file on the nginx scheduler


# vim /usr/local/nginx/conf/vhosts/lb.conf

Add the following:


upstream test {
  ip_hash;
  server 192.168.0.18;
  server 192.168.0.28;
}
server {
  listen 80;150
  server_name www.aminglinux.com;
  location / {
    proxy_pass http://test/;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  } 
}

3. Configuration instructions

You will find that this configuration is similar to the nginx proxy configuration we talked about before, except that there is one more upstream. This upstream is used to define RS at the back end, which can be written only once. ip_hash is a scheduling algorithm of nginx. Adding this 1 line will achieve the effect that the request of 1 user will be distributed to a fixed 1 RS moderately. This has the advantage of avoiding the loss of session by distributing requests from the same user to different machines. In upstream, ip after RS can also be weighted, such as "server 192.168.31.100 weight=100;" . One more thing to note is that test after upstream is a custom name, which can be written as you like. The only requirement of the 1 is to keep the 1 after proxy_pass.


Related articles: