nginx负载均衡

一.负载均衡

  1.概述

Web服务器,直接面向用户,往往要承载大量并发请求,单台服务器难以负荷,我使用多台WEB服务器组成集群,前端使用Nginx负载均衡,将请求分散的打到我们的后端服务器集群中,
实现负载的分发。那么会大大提升系统的吞吐率、请求性能、高容灾

  2.负载均衡的代理的区别

Nginx要实现负载均衡需要用到proxy_pass代理模块配置

Nginx负载均衡与Nginx代理不同地方在于

Nginx代理仅代理一台服务器,而Nginx负载均衡则是将客户端请求代理转发至一组upstream虚拟服务池

Nginx可以配置代理多台服务器,当一台服务器宕机之后,仍能保持系统可用。

 

二.简单实现负载均衡

  1. 准备第三台机器

1. nginx负载均衡器  192.168.226.130

2. 另外两台应用服务器(192.168.226.128 192.168.12.115)

  2.确保应用服务器和负载均衡器在实现负载均衡的之前都能单独访问

  3.配置负载均衡器(192.168.226.130)

      1.在nginx.conf > http 区域中

  upstream dajiba_fuzai {
        server 192.168.226.128;
        server 192.168.12.115;
        }

      2.在nginx.conf > http 区域 >  server区域  > location配置中

      添加proxy_pass

location / {
            #proxy_pass http://192.168.226.128;         
            proxy_pass http://dajiba_fuzai;
            root   html;
            index  index.html index.htm;
        }

      3.效果

vim /opt/nginx113/conf/nginx.conf


http {
  include mime.types;
  default_type application/octet-stream;


  #log_format main '$remote_addr - $remote_user [$time_local] "$request" '
  # '$status $body_bytes_sent "$http_referer" '
  # '"$http_user_agent" "$http_x_forwarded_for"';


  #access_log logs/access.log main;


  sendfile on;
  #tcp_nopush on;


  #keepalive_timeout 0;
  keepalive_timeout 65;


  #gzip on;
  upstream dajiba_fuzai {
  server 192.168.226.128;
  server 192.168.12.115;
  }


  server {
  listen 80;
  server_name localhost;


  #charset koi8-r;


  #access_log logs/host.access.log main;


  location / {
  #proxy_pass http://192.168.226.128;
  proxy_pass http://dajiba_fuzai;
  root html;
  index index.html index.htm;
  }

}

   4.平滑重启负载均衡器

/opt/ngix113/sbin/nginx -s reload

  5.访问负载均衡器(192.168.226.130)

并一直刷新,看看是否访问的页面一会儿是应用1.一会儿是应用二的

三.参数详解

  1.upstream分配策略

    weight 权重

  upstream dajiba_fuzai {
        server 192.168.226.128 weight=5;
        server 192.168.12.115  weight=10; #访问频率比较高
        }

    ip_hash

每个请求按访问ip的hash结果分配,这样每个访客固定访问一个后端服务器

  upstream dajiba_fuzai {
     ip_hash; server 192.168.226.128 weight=5; server 192.168.12.115 weight=10; #访问频率比较高 }
  

    backup

    在非backup机器繁忙或者宕机时,请求backup机器,因此机器默认压力最小

  upstream dajiba_fuzai {
     ip_hash;
        server 192.168.226.128 weight=5;
        server 192.168.12.115  weight=10; #访问频率比较高
    
server node.oldboy.com:8080 backup;

} 

   2.关闭防火墙

iptables -F
sed  -i 's/enforcing/disabled/' /etc/selinux/config

systemctl stop firewalld
systemctl disable firewalld
原文地址:https://www.cnblogs.com/tjp40922/p/10725635.html