nginx负载均衡和自动容灾(故障转移)配置
负载均衡
负载均衡部分是非常简单的。
upstream my_http {
server 127.0.0.1:8080 weight=1;
server 127.0.0.1:9090 weight=2;
}
server {
listen 80;
listen [::]:80;
# security
include nginxconfig.io/security.conf;
location / {
include nginxconfig.io/proxy.conf;
proxy_pass http://my_http;
}
}
重点就在于upstream部分。此处需要先定义一个upstream,然后在下方引用即可。
分配方式在upstream块中定义即可。
nginx的upstream目前支持5种方式的分配
1、轮询(默认)
每个请求按时间顺序逐一分配到不同的后端服务器,如果后端服务器down掉,能自动剔除。
2、weight
指定轮询几率,weight和访问比率成正比,用于后端服务器性能不均的情况。
3、ip_hash
每个请求按访问ip的hash结果分配,这样每个访客固定访问一个后端服务器,可以解决session的问题。
upstream bakend {
ip_hash;
server 192.168.203.14:88;
server 192.168.203.15:80;
}
4、fair(第三方)
按后端服务器的响应时间来分配请求,响应时间短的优先分配。
upstream bakend {
fair;
server 192.168.203.14:88;
server 192.168.203.15:80;
}
5、url_hash(第三方)
按访问url的hash结果来分配请求,使每个url定向到同一个后端服务器,后端服务器为缓存时比较有效。
自动容灾(故障转移)
下面就是本文的重头戏,关于nginx的自动容灾(故障转移)部分。
所谓自动容灾(故障转移),就是在后台服务器中出现故障时,能够自动转移到健康的服务器上,来维持整个服务的稳定。
配置也是比较简单的,在负载均衡的基础上添加一些配置即可。重点在于两段加了注释的内容,其余的都是装饰。
轮询服务器,weight为服务器权重,与访问频率成正比,max_fails最大超时次数,fail_timeout服务器代理监听超时时间
upstream backend_server {
server 192.168.203.43:80 weight=1 max_fails=2 fail_timeout=10s;
server 192.168.203.44:80 weight=1 max_fails=2 fail_timeout=10s;
server 192.168.203.45:80 weight=1 max_fails=2 fail_timeout=10s;
}
server {
listen 80;
listen [::]:80;
# security
include nginxconfig.io/security.conf;
location / {
#如果后端的服务器返回502、504、执行超时等错误,自动将请求转发到upstream负载均衡池中的另一台服务器,实现故障转移。
proxy_next_upstream http_502 http_504 error timeout invalid_header;
#设置一些超时时间。可选
proxy_next_upstream_timeout 1s;
proxy_next_upstream_tries 2;
proxy_connect_timeout 1s;
proxy_read_timeout 1s;
proxy_send_timeout 1s;
include nginxconfig.io/proxy.conf;
proxy_pass http://my_http;
}
}