普通配置
upstream www {
server 172.17.0.2;
server 172.17.0.3;
}
server {
listen 80;
listen [::]:80;
server_name 172.17.0.4;
client_max_body_size 1024m;
location / {
proxy_pass http://www;
proxy_set_header HOST $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
随机分配后端服务器
自定义权重
upstream www {
server 172.17.0.2 weight=6;
server 172.17.0.3 weight=3;
}
server {
listen 80;
listen [::]:80;
server_name 172.17.0.4;
client_max_body_size 1024m;
location / {
proxy_pass http://www;
proxy_set_header HOST $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
权重越大,被访问的次数就越多
权重+哈希
upstream www {
ip_hash;
server 172.17.0.2 weight=6;
server 172.17.0.3 weight=3;
}
server {
listen 80;
listen [::]:80;
server_name 172.17.0.4;
client_max_body_size 1024m;
location / {
proxy_pass http://www;
proxy_set_header HOST $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
在 upstream 指令块中增加了
ip_hash
指令。该指令就是告诉 nginx 服务器,同一个 IP 地址客户端发送的请求都将分发到同一个 后端服务器进行处理,此类一般用于有登录操作的场景
服务器状态负载
upstream www {
server 172.17.0.2 weight=6;
server 172.17.0.3 weight=3;
fair;
}
server {
listen 80;
listen [::]:80;
server_name 172.17.0.4;
client_max_body_size 1024m;
location / {
proxy_pass http://www;
proxy_set_header HOST $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
根据服务器处理请求的时间来进行负载,处理请求越快,也就是响应时间越短的优先分配