使用 nginx 实现后端 HTTP 服务器的故障转移(failover)
一般情况下,nginx 的 upstream 通常的用途是实现负载均衡:
但是实际上,nginx 对 upstream 的多个设备可以设置不同的状态参数:
- weight 默认为1. weight越大,负载的权重就越大;
- max_fails : 允许请求失败的次数默认为1. 当超过最大次数时,返回proxy_next_upstream 模块定义的错误;
- fail_timeout: max_fails 次失败后,暂停的时间;
- down 表示当前的server暂时不参与负载;
- backup: 其它所有的非 backup 机器 down 或者忙的时候,请求 backup 机器(所以这台机器压力会最轻);
因此,upstream 同样可以用于配置 “故障转移”的服务器集群,一般用于这类场景:一般情况下优先使用服务器1,只有这台服务器出故障后才转移到其他的服务器(因为其他服务器性能、网络速度不如服务器1等原因),下面就是一个配置的例子:
worker_processes 1; events { worker_connections 1024; } http { default_type application/octet-stream; client_max_body_size 4m; keepalive_timeout 65; upstream backend_servers { server localhost:7001 max_fails=3 fail_timeout=30s; # 下面两行 "backup" 只有在上面 "7001" 服务器失败后才会被访问(此时两台服务器会采用同样的权重进行负载均衡) server localhost:7002 max_fails=3 fail_timeout=30s backup; server localhost:7003 max_fails=3 fail_timeout=30s backup; # 如果为上面两行 "backup" 设定悬殊的 "weight" 参数,可以控制 failover 的顺序(比如设置只有 "7002" 宕机后才会访问到 "7003") #server localhost:7002 max_fails=3 fail_timeout=30s backup weight=2000000000; #server localhost:7003 max_fails=3 fail_timeout=30s backup weight=1; } server { listen 8001; server_name example.com; location / { proxy_pass http://backend_servers; } } }
附件 test-http-server.py 和 nginx.conf 是用于测试的 Python HTTP 服务器和 nginx 配置:
- 首先依次通过如下命令启动 3 台后端 HTTP 服务器:
python test-http-server.py 7001 python test-http-server.py 7002 python test-http-server.py 7003
- 然后使用如下命令启动 nginx 服务器:
# 启动 nginx nginx -c `pwd`/nginx.conf # 停止 nginx nginx -c `pwd`/nginx.conf -s quit
- 通过浏览器访问类似这样的 URL: http://localhost:8001/TEST/001
- 正常结果应该是 localhost 7001;
- 如果停止相应的服务器,可以看到浏览器上的输出切换到后续其他服务器(输出 localhost 7002、localhost 7003)
Attachments (3)
- 20170506-231144-780x584.png (73.2 KB) - added by thinkbase 22 months ago.
- test-http-server.py (1.1 KB) - added by thinkbase 22 months ago.
- nginx.conf (645 bytes) - added by thinkbase 22 months ago.
Download all attachments as: .zip
Comments
No comments.