负载均衡(Load Balancing)是将网络流量分发到多个服务器的技术,目的是优化资源使用、最大化吞吐量、减少响应时间,并避免单点故障。
upstream backend {
server backend1.example.com;
server backend2.example.com;
server backend3.example.com;
}
upstream backend {
server backend1.example.com weight=5;
server backend2.example.com max_fails=3 fail_timeout=30s;
server backend3.example.com backup;
}
weight
:权重,默认为1max_fails
:最大失败次数,超过后标记为不可用fail_timeout
:失败超时时间backup
:备用服务器down
:标记服务器永久不可用upstream backend {
server backend1.example.com;
server backend2.example.com;
}
upstream backend {
server backend1.example.com weight=3;
server backend2.example.com weight=2;
}
upstream backend {
ip_hash;
server backend1.example.com;
server backend2.example.com;
}
upstream backend {
least_conn;
server backend1.example.com;
server backend2.example.com;
}
upstream backend {
fair;
server backend1.example.com;
server backend2.example.com;
}
http {
upstream backend {
least_conn;
server 192.168.1.100:8080 weight=5 max_fails=3 fail_timeout=30s;
server 192.168.1.101:8080 weight=3;
server 192.168.1.102:8080 backup;
keepalive 32;
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# 健康检查相关
proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
proxy_connect_timeout 2s;
proxy_read_timeout 5s;
proxy_send_timeout 5s;
}
}
}
upstream backend {
server 192.168.1.100:8080;
server 192.168.1.101:8080;
keepalive 32; # 保持的连接数
}
upstream backend {
hash $cookie_jsessionid;
server 192.168.1.100:8080;
server 192.168.1.101:8080;
}
商业版Nginx Plus支持主动健康检查:
upstream backend {
zone backend 64k;
server 192.168.1.100:8080;
server 192.168.1.101:8080;
health_check interval=5s fails=3 passes=2 uri=/health;
}
开源版可通过第三方模块或被动检查实现:
proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
proxy_connect_timeout
值通过以上配置和优化,Nginx可以成为一个高效、可靠的负载均衡解决方案。