upstream 七层负载模块
Syntax: upstream name { ... }
Default: —
Context: http
Example:
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;
}
例子:
upstream rongbiz { --- 指定负载均衡主机信息
server 10.0.0.7:80;
server 10.0.0.8:80;
server 10.0.0.9:80;
}
server {
listen 80;
server_name www.rongbiz.com;
location / {
proxy_pass http://rongbiz; --- 将请求反向代理发送给哪个集群
include proxy_params;
}
}
Nginx负载均衡状态配置
后端服务器在负载均衡调度中的状态
状态 | 概述 |
---|---|
down | 当前的server暂时不参与负载均衡 |
backup | 预留的备份服务器 |
max_fails | 允许请求失败的次数 |
fail_timeout | 经过max_fails失败后, 服务暂停时间 |
max_conns | 限制最大的接收连接数 |
测试backup以及down状态
upstream load_pass {
server 192.168.56.11:8001 down;
server 192.168.56.12:8002 backup;
server 192.168.56.13:8003 max_fails=1 fail_timeout=10s;
}
location / {
proxy_pass http://load_pass;
include proxy_params;
}
Nginx负载均衡调度策略
调度算法 | 概述 |
---|---|
轮询 | 按时间顺序逐一分配到不同的后端服务器(默认) |
weight | 加权轮询,weight值越大,分配到的访问几率越高 |
ip_hash | 每个请求按访问IP的hash结果分配,这样来自同一IP的固定访问一个后端服务器 |
url_hash | 按照访问URL的hash结果来分配请求,是每个URL定向到同一个后端服务器 |
least_conn | 最少链接数,那个机器链接数少就分发 |
hash关键数值 | hash自定义的key |
Nginx负载均衡权重轮询具体配置
upstream load_pass {
server 192.168.56.11:8001;
server 192.168.56.12:8002 weight=5;
server 192.168.56.13:8003;
}
Nginx负载均衡ip_hash具体配置
//如果客户端都走相同代理, 会导致某一台服务器连接过多
upstream load_pass {
ip_hash;
server 192.168.56.11:8001;
server 192.168.56.12:8002;
server 192.168.56.13:8003;
}
//如果出现通过代理访问会影响后端节点接收状态均衡
Nginx负载均衡url_hash具体配置
upstream load_pass {
hash $request_uri;
server 192.168.56.11:8001;
server 192.168.56.12:8002;
server 192.168.56.13:8003;
}
//针对三台服务器添加相同文件
/soft/code1/url1.html url2.html url3.html
/soft/code2/url1.html url2.html url3.html
/soft/code3/url1.html url2.html url3.html
nginx四层负载均衡
Nginx负载均衡TCP配置
Nginx四层代理仅能存在于main段
stream {
upstream ssh_proxy {
hash $remote_addr consistent;
server 192.168.56.103:22;
}
upstream mysql_proxy {
hash $remote_addr consistent;
server 192.168.56.103:3306;
}
server {
listen 6666;
proxy_connect_timeout 1s;
proxy_timeout 300s;
proxy_pass ssh_proxy;
}
server {
listen 5555;
proxy_connect_timeout 1s;
proxy_timeout 300s;
proxy_pass mysql_proxy;
}
}