Nginx负载均衡实现


一、负载均衡方式
1、轮询

upstream test_up {
    server localhost:8080;   
            server localhost:9090;   
            server localhost:9090;
}

server {
      listen 80;
      server_name test;

      location /test.html {
            proxy_pass http://test_up;
      }}

以上代码当在浏览器地址栏中输入http://test/test.html时,nginx会按test_up中配置的服务器顺序依次访问后端服务器

2、权重分配

upstream test_up {
    server localhost:8080 weight=1;
    server localhost:9090 weight=2;
}

server {
      listen 80;
      server_name test;

      location /test.html {
            proxy_pass http://test_up;
      }
}

以上代码NGINX会根据权重值的分布,动态将前端请求分配给后端服务器

3、IP HASH分配

upstream test_up {
    server localhost:8080 weight=1;
    server localhost:9090 weight=2;
    ip_hash;
}

server {
    listen 80;
    server_name test;

    location /test.html {
        proxy_pass http://test_up
    }
}

IP HASH方式是根据客户端IP进行HASH后,将客户端请求分配给后端服务器

特别注意:上面代码中虽然在每个server后面配置了权重,但采用了IP HASH方式后,实际上权重并不会生效

二、对SERVER进行控制
1.down 表示单前的server暂时不参与负载
2.weight 默认为1.weight越大,负载的权重就越大。
3.max_fails :允许请求失败的次数默认为1.当超过最大次数时,返回proxy_next_upstream 模块定义的错误
4.fail_timeout:max_fails次失败后,暂停的时间。
5.backup: 其它所有的非backup机器down或者忙的时候,请求backup机器。所以这台机器压力会最轻。

nginx支持同时设置多组的负载均衡,用来给不用的server来使用。
client_body_in_file_only 设置为On 可以讲client post过来的数据记录到文件中用来做debug
client_body_temp_path 设置记录文件的目录 可以设置最多3层目录
location 对URL进行匹配.可以进行重定向或者进行新的代理 负载均衡

--------------------------------------分割线 --------------------------------------

Nginx反向代理搭建配置及搭建过程一些思考 

CentOS 6.2实战部署Nginx+MySQL+PHP

使用Nginx搭建WEB服务器

搭建基于Linux6.3+Nginx1.2+PHP5+MySQL5.5的Web服务器全过程

CentOS 6.3下Nginx性能调优

CentOS 6.3下配置Nginx加载ngx_pagespeed模块

CentOS 6.4安装配置Nginx+Pcre+php-fpm

Nginx安装配置使用详细笔记

Nginx日志过滤 使用ngx_log_if不记录特定日志

Nginx 的详细介绍:请点这里
Nginx 的下载地址:请点这里

本文永久更新链接地址:

相关内容