2.1 http lb
使用的是http module,在nginx.conf中http block内使用upstream block:
upstream backend {
server IP:port weigth=1;
FQDN;
unix socket backup;
}
server {
location / {
proxy_pass http://backend;
}
}
2.2 tcp lb
使用的是stream module,需要在nginx.conf中打开:
stream {
include /etc/nginx/stream.conf.d/*.conf;
}
然后在/etc/nginx/stream.conf.d/目录下创建example.conf文件:
upstream mysql_read {
#必须加端口
server read1.example.com:3306 weight=5;
server read2.example.com:3306;
server localhost:3306 backup;
}
server {
listen 3306;
proxy_pass mysql_read;
}
centos7上安装mariadb客户端,使用mysql -h127.0.0.1 -utlb -p123456 -e "show databases"可以实现负载均衡
2.3 udp lb
和tcp相同,在listen指令后面加udp参数
下例为将某个服务连接代理到本地:
stream {
server {
listen 1195 udp reuseport;
proxy_pass 127.0.0.1:1194;
}
}
使用了rsyslog服务的负载均衡,用logger命令,需要在/etc/rsyslog.conf文件中设置*.* @127.0.0.1:514,只有单台可以反向代理到后端;后来更换为random算法是可以的
2.4 Load-Balancing Methods
1.wrr //默认算法,没有名称,不用专门写,只写weight就行
2.least_conn //也会考虑权重,计算的是通过反向代理至后端的连接数;那与rr有什么区别
3.least_time //只有plus中存在,需要指定header或者last_byte参数
4.hash //可选参数consistent
5.random [ two [method] ] //随机选取
6.ip_hash //以客户端IP地址(IPv4前24位或整个IPv6地址)进行hash计算,只能用于HTTP的负载均衡
2.9 Passive Health Checks
upstream backend {
server backend1.example.com:1234 max_fails=3 fail_timeout=3s;
server backend2.example.com:1234 max_fails=3 fail_timeout=3s;
}
被动检查默认启用,在将客户端请求代理至后端时进行检查,适用于HTTP、TCP和UDP
2.10 Active Health Checks (Plus)
http {
server {
...
location / {
proxy_pass http://backend;
health_check interval=2s
fails=2
passes=5
uri=/
match=welcome;
}
}
# status is 200, content type is "text/html",
# and body contains "Welcome to nginx!"
match welcome {
status 200;
header Content-Type = text/html;
body ~ "Welcome to nginx!";
}
}
TCP/UDP
stream {
...
server {
listen 1234;
proxy_pass stream_backend;
health_check interval=10s
passes=2
fails=3
match=ahc;
health_check_timeout 5s;
}
match ahc {
send ...;
expect ...;
}
}
2.11 Slow Start(Plus)
upstream {
zone backend 64k;
server server1.example.com slow_start=20s;
server server2.example.com slow_start=15s;
}