Nginx实现负载均衡

Linux 发表时间:2021-10-28 11:25:49 作者:梁子亮 浏览次数:1210

修改loadbalance.conf,新增 location / 的配置,注意注释掉 include /home/wwwroot/nginx_rewrite.conf此句(其余配置不用变动),不然会跟location /的配置冲突

listen 80 ;
server_name lb.lziang.com;
location / {
    proxy_pass http://tim-server;
    proxy_redirect default;
}
index index.php index.html index.htm;
root  /home/wwwroot/lb;
#include /home/wwwroot/nginx_rewrite.conf;

修改loadbalance.conf,在service的同级新增以下, 注意tim-server是上面的proxy_pass中起的名称,可随便起

upstream  tim-server {
    server    lb.lziang.com:10001 weight=1;
    server    lb.lziang.com:10002 weight=2;
}

再次修改loadbalance.conf,按照平时的设置10001端口即可,注意需要打开刚才注释掉的include /home/wwwroot/nginx_rewrite.conf此句

  server
           {
                   listen 10001 ;
                   server_name lb.lziang.com;
                   index index.php index.html index.htm;
                   root  /home/wwwroot/lb;
                   include /home/wwwroot/nginx_rewrite.conf;
                   #error_page   404   /404.html;
                   location ~ [^/]\.php(/|$)
                          {
                                  # comment try_files $uri =404; to enable pathinfo
                                  try_files $uri =404;
                                  fastcgi_pass  unix:/tmp/php-cgi.sock;
                                  fastcgi_index index.php;
                                  include fastcgi.conf;
                                  #include pathinfo.conf;
                          }

                  location /nginx_status {
                          stub_status on;
                          access_log   off;
                  }

                  location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
                          {
                                  expires      30d;
                          }

                  location ~ .*\.(js|css)?$
                          {
                                  expires      12h;
                          }

                  access_log  /home/wwwlogs/access.log;
          }

重启nginx,需要打开外网的10001和10002端口,大功告成

另外,可以关注默认的max_fails=1 fail_timeout=10s参数,指10秒内发生1次错误,则把负载均衡的服务器剔除掉。可以更改为以下

upstream  tim-server {
    server    lb.lziang.com:10001 max_fails=2 fail_timeout=10s weight=1;
    server    lb.lziang.com:10002 max_fails=2 fail_timeout=10s weight=2;
}

另外,可以关注 location 下的(不是upstream下的)proxy_connect_timeout ,默认未60s,表示60秒负载均衡服务器没返回,则自动发送到另一台负载均衡服务器。可以更改为1秒(注意1s中的s是否可以省略 ? 未测试不得而知)

proxy_connect_timeout 1s;
proxy_read_timeout 1s
proxy_send_timeout 1s;