web服务之nginx反向代理功能

nginx反向代理功能

反向代理:reverse proxy,指的是代理外网用户的请求到内部的指定的服务器,并将数据返回给用户的
一种方式,这是用的比较多的一种方式。
Nginx 除了可以在企业提供高性能的web服务之外,另外还可以将 nginx 本身不具备的请求通过某种预
定义的协议转发至其它服务器处理,不同的协议就是Nginx服务器与其他服务器进行通信的一种规范,
主要在不同的场景使用以下模块实现不同的功能

ngx_http_proxy_module: #将客户端的请求以http协议转发至指定服务器进行处理
ngx_http_upstream_module #用于定义为proxy_pass,fastcgi_pass,uwsgi_pass等指令引用的后
端服务器分组
ngx_stream_proxy_module:#将客户端的请求以tcp协议转发至指定服务器处理
ngx_http_fastcgi_module:#将客户端对php的请求以fastcgi协议转发至指定服务器助理
ngx_http_uwsgi_module: #将客户端对Python的请求以uwsgi协议转发至指定服务器处理

LVS和nginx的区别

LVS:是在内核的,同时它只是作为转发器,不会有监听端口,查看日志只能看到client和server端建立连接,看不到LVS

NGINX:是一个代理服务器,是一个服务有自己的监听端口,同时查看日志可以看到client跟NGINX的连接和NGINX跟后端server建立连接

实现 http 反向代理

官方文档: https://nginx.org/en/docs/http/ngx_http_proxy_module.html

http 协议反向代理
反向代理配置参数

#官方文档:https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_pass
proxy_pass;
#用来设置将客户端请求转发给的后端服务器的主机,可以是主机名(将转发至后端服务做为主机头首部)、IP
地址:端口的方式
#也可以代理到预先设置的主机群组,需要模块ngx_http_upstream_module支持
#示例:
location /web {
    index index.html;
    proxy_pass http://172.31.0.18:8080; #8080后面无uri,即无 / 符号,需要将location后面url 附加到proxy_pass指定的url后面,此行为类似于root
    #proxy_pass指定的uri不带斜线将访问的/web,等于访问后端服务器
    http://172.31.0.18:8080/web/index.html,即后端服务器配置的站点根目录要有web目录才可以被访问
    # http://nginx/web/index.html ==> http://172.31.0.18:8080/web/index.html
    proxy_pass http://172.31.0.18:8080/; #8080后面有uri,即有 / 符号,相当于置换,即访问/web时实际返回proxy_pass后面uri内容.此行为类似于alias
   #proxy_pass指定的uri带斜线,等于访问后端服务器的http://172.31.0.18:8080/index.html 内容返回给客户端
} # http://nginx/web/index.html ==> http://172.31.0.18:8080

#重启Nginx测试访问效果:
#curl -L http://www.longxuan.vip/web
#如果location定义其uri时使用了正则表达式模式(包括~,~*,但不包括^~),则proxy_pass之后必须不能
使用uri; 即不能有/ ,用户请求时传递的uri将直接附加至后端服务器之后
server {
   ...
   server_name HOSTNAME;
   location ~|~* /uri/ {
       proxy_pass http://host:port; #proxy_pass后面的url 不能加/
   }
   ...
}

http://HOSTNAME/uri/ --> http://host/uri/
   proxy_hide_header field;
   #用于nginx作为反向代理的时候,在返回给客户端http响应时,隐藏后端服务器相应头部的信息,可以设置在http,server或location块
   #示例: 隐藏后端服务器ETag首部字段
location /web {
    index index.html;
    proxy_pass http://172.31.0.18:8080/;
    proxy_hide_header ETag;
}

    proxy_pass_header field;
#默认nginx在响应报文中不传递后端服务器的首部字段Date, Server, X-Pad, X-Accel等参数,如果要传递的话则要使用 proxy_pass_header field声明将后端服务器返回的值传递给客户端
#field 首部字段大小不敏感
#示例:透传后端服务器的Server和Date首部给客户端,同时不再响应报中显示前端服务器的Server字段
    proxy_pass_header Server;
    proxy_pass_header Date;

    proxy_pass_request_body on | off;
#是否向后端服务器发送HTTP实体部分,可以设置在http,server或location块,默认即为开启

    proxy_pass_request_headers on | off;
#是否将客户端的请求头部转发给后端服务器,可以设置在http,server或location块,默认即为开启

    proxy_set_header;
#可更改或添加客户端的请求头部信息内容并转发至后端服务器,比如在后端服务器想要获取客户端的真实IP
的时候,就要更改每一个报文的头部
#示例:
    #proxy_set_header X-Forwarded-For
    $proxy_add_x_forwarded_for;
    
$proxy_add_x_forwarded_for the “X-Forwarded-For” 
client request header field with the $remote_addr variable appended to it, separated by a comma. If the “X-Forwarded-For” field is 
not present in the client request header, the $proxy_add_x_forwarded_for 
variable is equal to the $remote_addr variable.

    proxy_set_header X-Real-IP $remote_addr;
#添加HOST到报文头部,如果客户端为NAT上网那么其值为客户端的共用的公网IP地址,常用于在日之中记录
客户端的真实IP地址。
#在后端httpd服务器修改配置,添加日志记录X-Forwarded-For字段
    LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" \"%{XReal-IP}i\"" combined

#在后端服务器查看日志
[root@centos8 ~]# tail /var/log/httpd/access_log -f
172.31.0.8 - - [09/Oct/2021:21:50:57 +0800] "HEAD /static/index.html HTTP/1.0" 200
- "-" "curl/7.29.0" "172.31.0.7"

    proxy_connect_timeout time;
#配置nginx服务器与后端服务器尝试建立连接的超时时间,默认为60秒,用法如下:
    proxy_connect_timeout 6s;
#60s为自定义nginx与后端服务器建立连接的超时时间,超时会返回客户端504响应码
    proxy_read_timeout time;
#配置nginx服务器向后端服务器或服务器组发起read请求后,等待的超时时间,默认60s
    proxy_send_timeout time;
#配置nginx项后端服务器或服务器组发起write请求后,等待的超时 时间,默认60s

    proxy_http_version 1.0;
#用于设置nginx提供代理服务的HTTP协议的版本,默认http 1.0

    proxy_ignore_client_abort off;
#当客户端网络中断请求时,nginx服务器中断其对后端服务器的请求。即如果此项设置为on开启,则服务器
会忽略客户端中断并一直等着代理服务执行返回,如果设置为off,则客户端中断后Nginx也会中断客户端请
求并立即记录499日志,默认为off。

    proxy_headers_hash_bucket_size 128;
#当配置了 proxy_hide_header和proxy_set_header的时候,用于设置nginx保存HTTP报文头的hash
表的上限

    proxy_headers_hash_max_size 512;
#设置proxy_headers_hash_bucket_size的最大可用空间
    server_namse_hash_bucket_size 512;
#server_name hash表申请空间大小
server_names_hash_max_size 512;
#设置服务器名称hash表的上限大小
    proxy_next_upstream error | timeout | invalid_header | http_500 | http_502 |http_503 | http_504;
#当一台后端朋务器出错,超时,无效首部,500等时,切换至下一个后端服务器提供服务

实战案例: 反向代理单台 web 服务器

要求:将用户对域 www.longxuan.vip 的请求转发给后端服务器处理

[root@centos8 ~]# cat /apps/nginx/conf/conf.d/pc.conf
server {
    listen 80;
    server_name www.longxuan.vip;
    location / {
        proxy_pass http://172.31.0.37/; # http://172.31.0.37/ 最后的 / 可加或不加
    }
}
#重启Nginx 并访问测试

注意:

如果后端服务器无法连接((比如:iptables -AINPUT -s nginx_ip -j REJECT或者systemctl stop httpd)), 会出现提示502 Bad Gateway

默认在1分钟内后端服务器无法响应(比如:iptables -AINPUT -s nginx_ip -j DROP),会显示“504 Gateway Time-out”超时提示

实战案例: 指定 location 实现反向代理

针对指定的 location

server {
    listen 80;
    server_name www.longxuan.vip;
    location / {
        index index.html index.php;
        root /data/nginx/html/pc;
    }
    location /static {
        #proxy_pass http://172.31.0.37:80/; #注意有后面的/, 表示置换
        proxy_pass http://172.31.0.37:80; #后面没有 / , 表示附加
    }
}

#后端web服务器必须要有相对于的访问URL
[root@centos8 ~]# mkdir /var/www/html/static
[root@centos8 ~]# echo "web1 page for apache" > /var/www/html/index.html
[root@centos8 ~]# echo "web2 page for apache" > /var/www/html/static/index.html

#重启Nginx并访问测试:
[root@centos8 ~]# curl -L http://www.longxuan.vip/
pc web
[root@centos8 ~]# curl -L http://www.longxuan.vip/static
web2 page for apache

#Apache的访问日志:
[root@centos8 ~]# tail -f /var/log/httpd/access_log
172.31.0.27 - - [13/Jun/2021:20:38:09 +0800] "GET /static HTTP/1.0" 301 234 "-" "curl/7.29.0"
172.31.0.17 - - [13/Jun/2021:20:38:09 +0800] "GET /static/ HTTP/1.1" 200 21 "-" "curl/7.29.0"

针对特定的资源实现代理

[root@centos8 ~]# vim /apps/nginx/conf/conf.d/pc.conf
server {
    ......
    location ~ \.(jpe?g|png|bmp|gif)$ {
        proxy_pass http://172.31.0.37; #如果加/ 语法出错
    }
}

#如果 http://172.31.0.37/ 有 / 语法出错
[root@localhost nginx]# nginx -t
nginx: [emerg] "proxy_pass" cannot have URI part in location given by regular expression, or inside named location, or inside "if" statement, or inside "limit_except" block in /apps/nginx/conf/conf.d/pc.conf:12
nginx: configuration file /apps/nginx/conf/nginx.conf test failed

反向代理示例: 缓存功能

缓存功能默认关闭状态,需要先动配置才能启用

proxy_cache zone_name | off; 默认off
#指明调用的缓存,或关闭缓存机制;Context:http, server, location
#zone_name 表示缓存的名称.需要由proxy_cache_path事先定义

proxy_cache_key string;
#缓存中用于“键”的内容,默认值:proxy_cache_key $scheme$proxy_host$request_uri;

proxy_cache_valid [code ...] time;
#定义对特定响应码的响应内容的缓存时长,定义在http{...}中
示例:
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;

proxy_cache_path;
#定义可用于proxy功能的缓存;Context:http
proxy_cache_path path [levels=levels] [use_temp_path=on|off]
keys_zone=zone_name:size [inactive=time] [max_size=size] [manager_files=number]
[manager_sleep=time] [manager_threshold=time] [loader_files=number]
[loader_sleep=time] [loader_threshold=time] [purger=on|off]
[purger_files=number] [purger_sleep=time] [purger_threshold=time];

#示例:在http配置定义缓存信息
proxy_cache_path /var/cache/nginx/proxy_cache #定义缓存保存路径,proxy_cache会自动创
建
levels=1:2:2   #定义缓存目录结构层次,1:2:2可以生成2^4x2^8x2^8=2^20=1048576个目录
keys_zone=proxycache:20m   #指内存中缓存的大小,主要用于存放key和metadata(如:使用次
数),一般1M可存放8000个左右的key
inactive=120s   #缓存有效时间
max_size=10g;   #最大磁盘占用空间,磁盘存入文件内容的缓存空间最大值

#调用缓存功能,需要定义在相应的配置段,如server{...};或者location等
proxy_cache proxycache;
proxy_cache_key $request_uri; #对指定的数据进行MD5的运算做为缓存的key
proxy_cache_valid 200 302 301 10m; #指定的状态码返回的数据缓存多长时间
proxy_cache_valid any 1m; #除指定的状态码返回的数据以外的缓存多长时间,必须设置,否则不会缓存

proxy_cache_use_stale error | timeout | invalid_header | updating | http_500 |
http_502 | http_503 | http_504 | http_403 | http_404 | off ; #默认是off
#在被代理的后端服务器出现哪种情况下,可直接使用过期的缓存响应客户端
#示例
proxy_cache_use_stale error http_502 http_503;

proxy_cache_methods GET | HEAD | POST ...;
#对哪些客户端请求方法对应的响应进行缓存,GET和HEAD方法总是被缓存
扩展知识: 清理缓存
方法1: rm -rf 缓存目录
方法2: 第三方扩展模块ngx_cache_purge

非缓存场景压测

#准备后端httpd服务器
[root@centos8 app1]# pwd
/var/www/html/static
[root@centos8 static]# cat /var/log/messages > ./log.html #准备测试页面
[root@centos8 ~]# ab -n 2000 -c200 http://www.longxuan.vip/static/log.html
Concurrency Level: 200
Time taken for tests: 15.363 seconds
Complete requests: 2000
...

准备缓存配置

[root@centos8 ~]# vim /apps/nginx/conf/nginx.conf
proxy_cache_path /data/nginx/proxycache levels=1:1:1 keys_zone=proxycache:20m
inactive=120s max_size=1g; #配置在nginx.conf http配置段

[root@centos8 ~]# vim /apps/nginx/conf/conf.d/pc.conf
location /static { #要缓存的URL 或者放在server配置项对所有URL都进行缓存
    proxy_pass http://172.31.0.18:80;
    proxy_cache proxycache;
    proxy_cache_key $request_uri;
    #proxy_cache_key $host$uri$is_args$args;
    proxy_cache_valid 200 302 301 10m;
    proxy_cache_valid any 5m; #必须指定哪些响应码的缓存
    proxy_set_header clientip $remote_addr;
}

[root@centos8 ~]# systemctl restart nginx
#/data/nginx/proxycache/ 目录会自动生成
[root@centos8 ~]# ll /data/nginx/proxycache/ -d
drwx------ 2 nginx root 6 Oct 10 11:30 /data/nginx/proxycache/
[root@centos8 ~]# tree /data/nginx/proxycache/
/data/nginx/proxycache/
0 directories, 0 files

访问并验证缓存文件

#访问web并验证缓存目录
[root@centos8 ~]# curl http://www.longxuan.vip/static/log.html
[root@centos8 ~]# ab -n 2000 -c200 http://www.longxuan.vip/static/log.html
Concurrency Level: 200
Time taken for tests: 8.165 seconds
Complete requests: 2000
...

#验证缓存目录结构及文件大小
[root@centos8 ~]# tree /data/nginx/proxycache/
/data/nginx/proxycache/
└── d
    └── b
        └── e
            └── a971fce2cfaae636d54c5121d7a74ebb
3 directories, 1 file

#验证文件内容:
[root@centos8 ~]# file
/data/nginx/proxycache/d/b/e/a971fce2cfaae636d54c5121d7a74ebb
/data/nginx/proxycache/d/b/e/a971fce2cfaae636d54c5121d7a74ebb: Hitachi SH bigendian
COFF object file, not stripped, 0 section, symbol offset=0x813a815f

[root@centos8 ~]# head -n20
/data/nginx/proxycache/d/b/e/a971fce2cfaae636d54c5121d7a74ebb
#会在文件首部添加相应码
...

添加响应报文的头部信息

nginx基于模块ngx_http_headers_module可以实现对后端服务器响应给客户端的报文中添加指定的响
应首部字段

参考链接: https://nginx.org/en/docs/http/ngx_http_headers_module.html

范例

Syntax: add_header name value [always];
Default: —
Context: http, server, location, if in location

#添加响应报文的自定义首部:
add_header name value [always];

#示例:
add_header X-Via $server_addr; #当前nginx主机的IP
add_header X-Cache $upstream_cache_status; #是否缓存命中
add_header X-Accel $server_name; #客户访问的FQDN

#添加自定义响应信息的尾部,使用较少,1.13.2版后支持
add_trailer name value [always];

Nginx 配置

location /static {
    proxy_pass http://172.31.0.101:80/;
    proxy_cache proxycache;
    proxy_cache_key $request_uri;
    proxy_cache_valid 200 302 301 1h;
    proxy_cache_valid any 1m;
    proxy_set_header clientip $remote_addr;
    add_header X-Via $server_addr;
    add_header X-Cache $upstream_cache_status;
    add_header X-Accel $server_name;
}

验证头部信息

[root@centos7 ~]# curl http://www.longxuan.vip/static/log.html -I
HTTP/1.1 200 OK
Date: Sat, 10 Oct 2021 03:42:31 GMT
Content-Type: text/html; charset=UTF-8
Content-Length: 743158
Connection: keep-alive
Vary: Accept-Encoding
Server: Apache/2.4.37 (centos)
Last-Modified: Sat, 10 Oct 2021 03:22:52 GMT
ETag: "b56f6-5b14894970c60"
X-Via: 172.31.0.8
X-Cache: MISS #第一次无缓存
X-Accel: www.longxuan.vip
Accept-Ranges: bytes
[root@centos7 ~]# curl http://www.longxuan.vip/static/log.html -I
HTTP/1.1 200 OK
Date: Sat, 10 Oct 2021 03:42:38 GMT
Content-Type: text/html; charset=UTF-8
Content-Length: 743158
Connection: keep-alive
Vary: Accept-Encoding
Server: Apache/2.4.37 (centos)
Last-Modified: Sat, 10 Oct 2021 03:22:52 GMT
ETag: "b56f6-5b14894970c60"
X-Via: 172.31.0.8
X-Cache: HIT #第二次命令缓存
X-Accel: www.longxuan.vip
Accept-Ranges: bytes

实现反向代理客户端 IP 透传

一级代理实现客户端IP透传
[root@centos8 ~]# cat /apps/nginx/conf/conf.d/pc.conf
server {
    listen 80;
    server_name www.longxuan.vip;
    location / {
        index index.html index.php;
        root /data/nginx/html/pc;
        proxy_pass http://172.31.0.37;
        #proxy_set_header X-Real-IP $remote_addr; #只添加客户端IP到请求报文头部,转发至后端服务器
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; #添加客户端IP和反向代理服务器IP到请求报文头部
    }
}

#重启nginx
[root@centos8 ~]#systemctl restart nginx

#后端Apache配置:
[root@centos8 ~]# vim /etc/httpd/conf/httpd.conf
LogFormat "%{X-Forwarded-For}i %h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined

#重启apache访问web界面并验证apache日志
[root@centos8 ~]# cat /var/log/httpd/access_log
172.31.0.1 172.31.0.27 - - [05/Mar/2021:00:40:46 +0800] "GET / HTTP/1.0" 200 19 "-"
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/72.0.3626.119 Safari/537.36"

#Nginx配置:
[root@centos8 conf.d]# cat /apps/nginx/conf/nginx.conf
"$http_x_forwarded_for"' #默认日志格式就有此配置
#重启nginx访问web界面并验证日志格式:
172.31.0.27 - - [04/Mar/2021:16:40:51 +0800] "GET / HTTP/1.0" 200 24 "-"
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/72.0.3626.119 Safari/537.36" "172.31.0.1"
多级代理实现客户端 IP 透传

范例: 多级代理实现IP透传

#第一个代理服务器
[root@nginx1 ~]# vim /apps/nginx/conf/nginx.conf
#开启日志格式,记录x_forwarded_for
http {
    include mime.types;
    default_type application/octet-stream;
    proxy_cache_path /data/nginx/proxycache levels=1:1:1
    keys_zone=proxycache:20m inactive=120s max_size=1g;
    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;
   
#定义反向代理
[root@nginx1 ~]# vim /apps/nginx/conf/conf.d/pc.conf
server {
    location / {
        proxy_pass http://172.31.0.37;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
    .......
}

#第二个代理服务器
[root@nginx2 ~]# vim /apps/nginx/conf/nginx.conf
##开启日志格式,记录x_forwarded_for
http {
    include mime.types;
    default_type application/octet-stream;
    proxy_cache_path /data/nginx/proxycache levels=1:1:1
    keys_zone=proxycache:20m inactive=120s max_size=1g;
    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;

#定义反向代理(在NGINX主配置文件添加如下即可)
[root@nginx2 ~]# vim /apps/nginx/conf/nginx.conf
server {
    location / {
        proxy_pass http://172.31.0.47;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
    .....
}

#在第一个proxy上面查看日志(前面的看到的IP是客户端)
[root@nginx1 ~]# tail /apps/nginx/logs/access.log -f
172.31.0.17 - - [11/Oct/2021:14:37:00 +0800] "GET /index.html HTTP/1.1" 200 11 "-"
"curl/7.58.0" "-"

#在第二个proxy上面查看日志(前看到的是上游服务器IP,后面看到是客户端的IP)
[root@nginx2 ~]# tail /apps/nginx/logs/access.log -f
172.31.0.27 - - [11/Oct/2021:14:37:00 +0800] "GET /index.html HTTP/1.0" 200 11 "-"
"curl/7.58.0" "172.31.0.17"

#后端服务器配置日志格式
[root@centos8 ~]# vim /etc/httpd/conf/httpd.conf
LogFormat "\"%{x-Forwarded-For}i\" %h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" testlog
CustomLog "logs/access_log" testlog

#测试访问
[root@centos7 ~]# curl www.longxuan.vip/index.html
<h1> web site on 172.31.0.47 </h1>

#后端服务器查看日志
[root@centos8 ~]# tail -f /var/log/httpd/access_log
"172.31.0.17, 172.31.0.27" 172.31.0.37 - - [11/Oct/2021:14:37:00 +0800] "GET
/index.html HTTP/1.0" 200 34 "-" "curl/7.29.0"

http 反向代理负载均衡

在上一个节中Nginx可以将客户端的请求转发至单台后端服务器但是无法转发至特定的一组的服务器,
而且不能对后端服务器提供相应的服务器状态监测,Nginx 可以基于ngx_http_upstream_module模块
提供服务器分组转发、权重分配、状态监测、调度算法等高级功能

官方文档: https://nginx.org/en/docs/http/ngx_http_upstream_module.html

http upstream配置参数

#自定义一组服务器,配置在http块内
upstream name {
    server .....
    ......
}
#示例
upstream backend {
    server backend1.example.com weight=5;
    server 127.0.0.1:8080 max_fails=3 fail_timeout=30s;
    server unix:/tmp/backend3;
    server backup1.example.com backup;
}

server address [parameters];
#配置一个后端web服务器,配置在upstream内,至少要有一个server服务器配置。
#server支持的parameters如下:
weight=number #设置权重,默认为1,实现类似于LVS中的WRR,WLC等
max_conns=number #给当前后端server设置最大活动链接数,默认为0表示没有限制
max_fails=number #后端服务器的下线条件,当客户端访问时,对本次调度选中的后端服务器连续进行检测
多少次,如果都失败就标记为不可用,默认为1次,当客户端访问时,才会利用TCP触发对探测后端服务器健康性
检查,而非周期性的探测
fail_timeout=time #后端服务器的上线条件,对已经检测到处于不可用的后端服务器,每隔此时间间隔再次
进行检测是否恢复可用,如果发现可用,则将后端服务器参与调度,默认为10秒
backup #设置为备份服务器,当所有后端服务器不可用时,才会启用此备用服务器
down #标记为down状态
resolve #当server定义的是主机名的时候,当A记录发生变化会自动应用新IP而不用重启Nginx

hash KEY [consistent];
#基于指定请求报文中首部字段或者URI等key做hash计算,使用consistent参数,将使用ketama一致性
hash算法,适用于后端是Cache服务器(如varnish)时使用,consistent定义使用一致性hash运算,一
致性hash基于取模运算
hash $request_uri consistent; #基于用户请求的uri做hash
hash $cookie_sessionid #基于cookie中的sessionid这个key进行hash调度,实现会话绑定

ip_hash;
#源地址hash调度方法,基于的客户端的remote_addr(源地址IPv4的前24位或整个IPv6地址)做hash计算,以实现会话保持

least_conn;
#最少连接调度算法,优先将客户端请求调度到当前连接最少的后端服务器,相当于LVS中的WLC

基于 hash 的调度算法

添加节点后,会导致很多的调度的缓存信息失效

一致性hash 算法

反向代理示例: 后端多台 web服务器
环境说明:
172.31.0.27 #Nginx 代理服务器
172.31.0.37 #后端web A,Apache部署
172.31.0.47 #后端web B,Apache部署

部署后端 Apache服务器
[root@centos8 ~]# yum install httpd -y
[root@centos8 ~]# echo "web1 172.31.0.37" > /var/www/html/index.html
[root@centos8 ~]# systemctl enable --now httpd
[root@centos8 ~]# yum install httpd -y
[root@centos8 ~]# echo "web2 172.31.0.47" >> /var/www/html/index.html
[root@centos8 ~]# systemctl enable --now httpd

#访问测试
[root@centos8 ~]# curl http://172.31.0.37
web1 172.31.0.37
[root@centos8 ~]# curl http://172.31.0.47
web2 172.31.0.47

配置 nginx 反向代理
注意: 本节实验过程中先关闭缓存
[root@centos8 ~]# cat /apps/nginx/conf/conf.d/pc.conf
http {
    upstream webserver {
    #hash $request_uri consistent;
    #hash $cookie_sessionid
    #ip_hash;
    #least_conn;
    server 172.31.0.37:80 weight=1 fail_timeout=5s max_fails=3; #后端服务器状态监测
    server 172.31.0.47:80 weight=1 fail_timeout=5s max_fails=3;
    #server 127.0.0.1:80 weight=1 fail_timeout=5s max_fails=3 backup;
}
server {
    listen 80;
    server_name www.longxuan.vip;
    location / {
    index index.html index.php;
    root /data/nginx/html/pc;
    }
location /web {
    index index.html;
    proxy_pass http://webserver/;
    proxy_next_upstream error timeout http_500;  #看情况添加
    }
}

#重启Nginx 并访问测试
[root@centos8 ~]# curl http://www.longxuan.vip/web
web1 172.31.0.37
[root@centos8 ~]# curl http://www.longxuan.vip/web
web2 172.31.0.47

#关闭172.31.0.37和172.31.0.47,测试nginx backup服务器可用性:
[root@centos8 ~]# while true;do curl http://www.longxuan.vip/web;sleep 1;done

#注意:
用nginx upstream 模块实现无感知部署
启用proxy_next_upstream 功能:在服务器返回502,504,错误,超时 的时候;允许转发到其他服务器;

proxy_next_upstream error | timeout | invalid_header | http_500 | http_502 | http_503 | http_504;
指定应将请求传递到下一个服务器的情况:
error             # 与服务器建立连接,向其传递请求或读取响应头时发生错误;
timeout           # 在与服务器建立连接,向其传递请求或读取响应头时发生超时;
invalid_header    # 服务器返回空的或无效的响应;
http_500          # 服务器返回代码为500的响应;
http_502          # 服务器返回代码为502的响应;
http_503          # 服务器返回代码为503的响应;
http_504          # 服务器返回代码504的响应;
http_403          # 服务器返回代码为403的响应;
http_404          # 服务器返回代码为404的响应;
http_429          # 服务器返回代码为429的响应;
non_idempotent    # 通常,请求与 非幂等 方法(POST,LOCK,PATCH)不传递到请求是否已被发送到上游服务器(1.9.13版本)的下一个服务器; 启用此选项显式允许重试此类请求;
off               # 禁用将请求传递给下一个服务器。

实战案例: 基于Cookie 实现会话绑定

[root@centos8 ~]#vim /apps/nginx/conf/nginx.conf
http {
    upstream websrvs {
    hash $cookie_hello; #hello是cookie的key的名称
    server 172.31.0.37:80 weight=2;
    server 172.31.0.47:80 weight-1;
    }
}
[root@centos8 ~]# vim /apps/nginx/conf/conf.d/pc.conf
server {
    location /{
        #proxy_cache mycache;
        proxy_pass http://websrvs;
    }
}

#测试
[root@centos8 ~]# curl -b hello=long http://www.longxuan.vip/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值