nginx反向代理(负载均衡)

反向代理的概念

代理一词,顾名思义就是代为处理,正向代理就是代替客户端处理,代替客户端进行各种服务的访问以及获取。那么反向代理自然就是代替服务器进行事务处理,即就是此时的代理服务器负责将用户的各项请求做一个汇总,分类,将其分发到不同的服务器上去进行处理。从而达到负载均衡和隐匿真实服务器的作用。
nginx作为性能怪兽,其最优秀的功能便是对反向代理的完美支持,本文将结合示例,了解反向代理的基本配置。

nginx的负载均衡策略

负载均衡用于从“upstream”模块定义的后端服务器列表中选取一台服务器接受用户的请求。一个最基本的upstream模块是这样的,模块内的server是服务器列表:

   #动态服务器组
    upstream dynamic_zuoyu {
        server localhost:8080;  #tomcat 7.0
        server localhost:8081;  #tomcat 8.0
        server localhost:8082;  #tomcat 8.5
        server localhost:8083;  #tomcat 9.0
    }

在upstream模块配置完成后,要让指定的访问反向代理到服务器列表:

        #其他页面反向代理到tomcat容器
        location ~ .*$ {
            index index.jsp index.html;
            proxy_pass http://dynamic_zuoyu;
        }

上文的大概意思就是从upstream模块种选取server中的一个用于某次客户请求的处理,那么如何选取处理请求的服务器便成为了一个十分重要的问题,为此nginx给出了一下几种方式;

轮询默认方式
weight权重方式
ip_hash依据ip分配方式
least_conn最少连接方式
fair(第三方)响应时间方式
url_hash(第三方)依据URL分配方式

1.轮询

最基本的配置方法,上面的例子就是轮询的方式,它是upstream模块默认的负载均衡默认策略。每个请求会按时间顺序逐一分配到不同的后端服务器。
参数如下:

fail_timeout — 与max_fails结合使用。
max_fails — 设置在fail_timeout参数设置的时间内最大失败次数,如果在这个时间内,所有针对该服务器的请求都失败了,那么认为该服务器会被认为是停机了,
fail_time — 服务器会被认为停机的时间长度,默认为10s。
backup — 标记该服务器为备用服务器。当主服务器停止时,请求会被发送到它这里。
down — 标记服务器永久停机了。

注意:

  • 在轮询中,如果服务器down掉了,会自动剔除该服务器。
  • 缺省配置就是轮询策略。
  • 此策略适合服务器配置相当,无状态且短平快的服务使用。

2.weight

权重方式,在轮询策略的基础上指定轮询的几率。例子如下:

upstream dynamic_zuoyu {
        server localhost:8080   weight=2;  #tomcat 7.0
        server localhost:8081;  #tomcat 8.0
        server localhost:8082   backup;  #tomcat 8.5
        server localhost:8083   max_fails=3 fail_timeout=20s;  #tomcat 9.0
    }

在该例子中,weight参数用于指定轮询几率,weight的默认值为1,;weight的数值与访问比率成正比,比如Tomcat 7.0被访问的几率为其他服务器的两倍。
注意:

  • 权重越高分配到需要处理的请求越多。
  • 此策略可以与least_conn和ip_hash结合使用。
  • 此策略比较适合服务器的硬件配置差别比较大的情况。

3.ip_hash

指定负载均衡器按照基于客户端IP的分配方式,这个方法确保了相同的客户端的请求一直发送到相同的服务器,以保证session会话。这样每个访客都固定访问一个后端服务器,可以解决session不能跨服务器的问题。

#动态服务器组
    upstream dynamic_zuoyu {
        ip_hash;    #保证每个访客固定访问一个后端服务器
        server localhost:8080   weight=2;  #tomcat 7.0
        server localhost:8081;  #tomcat 8.0
        server localhost:8082;  #tomcat 8.5
        server localhost:8083   max_fails=3 fail_timeout=20s;  #tomcat 9.0
    }

注意:

  • 在nginx版本1.3.1之前,不能在ip_hash中使用权重(weight)
  • ip_hash不能与backup同时使用。
  • 此策略适合有状态服务,比如session。
  • 当有服务器需要剔除,必须手动down掉。

4.least_conn

把请求转发给连接数较少的后端服务器。轮询算法是把请求平均的转发给各个后端,使它们的负载大致相同;但是,有些请求占用的时间很长,会导致其所在的后端负载较高。这种情况下,least_conn这种方式就可以达到更好的负载均衡效果。

#动态服务器组
    upstream dynamic_zuoyu {
        least_conn;    #把请求转发给连接数较少的后端服务器
        server localhost:8080   weight=2;  #tomcat 7.0
        server localhost:8081;  #tomcat 8.0
        server localhost:8082 backup;  #tomcat 8.5
        server localhost:8083   max_fails=3 fail_timeout=20s;  #tomcat 9.0
    }

注意:此负载均衡策略适合请求处理时间长短不一造成服务器过载的情况。

5.第三方策略

5.1 fair

按照服务器端的响应时间来分配请求,响应时间短的优先分配.

 #动态服务器组
    upstream dynamic_zuoyu {
        server localhost:8080;  #tomcat 7.0
        server localhost:8081;  #tomcat 8.0
        server localhost:8082;  #tomcat 8.5
        server localhost:8083;  #tomcat 9.0
        fair;    #实现响应时间短的优先分配
    }

5.2 url_hash

按访问url的hash结果来分配请求,使每个url定向到同一个后端服务器,要配合缓存命中来使用。同一个资源多次请求,可能会到达不同的服务器上,导致不必要的多次下载,缓存命中率不高,以及一些资源时间的浪费。而使用url_hash,可以使得同一个url(也就是同一个资源请求)会到达同一台服务器,一旦缓存住了资源,再此收到请求,就可以从缓存中读取。

#动态服务器组
    upstream dynamic_zuoyu {
        hash $request_uri;    #实现每个url定向到同一个后端服务器
        server localhost:8080;  #tomcat 7.0
        server localhost:8081;  #tomcat 8.0
        server localhost:8082;  #tomcat 8.5
        server localhost:8083;  #tomcat 9.0
    }

nginx反向代理的配置方法

1.环境配置

准备三台配置了nginx的服务器。
在这里插入图片描述
在1/2上分别配置不同的web页面

#关闭防火墙
[root@blackstone ~]# systemctl stop firewalld
[root@blackstone ~]# systemctl disable firewalld
#初始化配置文件
[root@blackstone ~]# rm -f /etc/nginx/nginx.conf
[root@blackstone ~]# cp /usr/local/nginx/conf/nginx.conf.default /etc/nginx/nginx.conf
[root@blackstone ~]# vim /etc/nginx/nginx.conf
--------------------------------------------------------------
#将配置文件内部的此行修改以指定工作目录(网页根目录)
 location / {
            root   /var/www/html;   #指定根目录
            index  index.html index.htm;
        }
--------------------------------------------------------------
#写入网页
[root@blackstone ~]# mkdir -p /var/www/html
[root@blackstone ~]# echo lalala-192.168.2.163 > /var/www/html/index.html
#启动nginx
[root@blackstone ~]# nginx

另一台服务器相同配置。
在这里插入图片描述
在这里插入图片描述

2.反向代理配置

在第三台服务器上配置反向代理

[root@blackstone ~]# rm -f /etc/nginx/nginx.conf
[root@blackstone ~]# cp /usr/local/nginx/conf/nginx.conf.default /etc/nginx/ngin                                                                                       x.conf
[root@blackstone ~]# vim /etc/nginx/nginx.conf

示例配置文件:

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


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 nginx_reverse{
        # 30s内检查心跳发送两次包,未回复就代表该机器宕机,请求分发权重比为1:2
        server 192.168.2.162 weight=100 max_fails=2 fail_timeout=30s; 
        server 192.168.2.163 weight=200 max_fails=2 fail_timeout=30s;
        # 这里的IP请配置成你WEB服务所在的机器IP
        }
    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
        #再此处使用location调用负载均衡策略
    	location / {
    	#设置根目录
       	 root   /var/www/html;
       	 index  index.html index.htm;
       	 proxy_set_header Host $host;
       	 proxy_set_header X-Real-IP $remote_addr;
       	 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
       	 # 请求交给名为nginx_reverse的upstream上
       	 proxy_pass http://nginx_reverse;
    	}
}


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}

配置完毕后重启nginx

[root@blackstone ~]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@blackstone ~]# nginx -s reload

进行测试:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
可以看到三次刷新我们的请求被发送到了两台服务器,占比为1:2

3.关于location的细节

nginx的配置是分块分层级进行的,最外层的块分为三个,分别是全局块、events块和http块。
在http块中又有server块是用来指定虚拟主机的模块,其中我们可以通过对location块的配置基于 Nginx 服务器接收到的请求字符串(例如 server_name/uri-string),对虚拟主机名称(也可以是 IP 别名)之外的字符串(例如 前面的 /uri-string)进行匹配,对特定的请求进行处理。地址定向、数据缓存和应答控制等功能,还有许多第三方模块的配置也在这里进行。

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;

    server {
        listen       80;
        server_name  localhost;

        # 若请求路径像这样:www.xxxx/img/example.png
        # 则访问/img/目录下的文件时,nginx会去/var/www/image/img/目录下找文件,就是对于网站的根目录进行指定
        location /img/ {
            root /var/www/image;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
    }
}

当然我们在浏览其他的博客时可能会发现,在location后边会附有一些特殊的符号;

location [ = | ~ | ~* | ^~] URL {...} 

这里紧跟着的符号也是大有作用的:

=用于不含正则表达式的 uri 前,要求请求字符串与 uri 严格匹配,如果匹配成功,就停止继续向下搜索并立即处理该请求
~用于表示 uri 包含正则表达式,并且区分大小写
~*用于表示 uri 包含正则表达式,并且不区分大小写
^~用于不含正则表达式的 uri 前,要求 Nginx 服务器找到标识 uri 和请求字符串匹配度最高的 location 后,立即使用此 location 处理请求,而不再使用 location块中的正则 uri 和请求字符串做匹配。

这里需要注意的是我们在使用正则表达式进行URL匹配时,前面一定要添加~或者~*

本文参考链接:
nginx的负载均衡策略
nginx配置—反向代理

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值