Nginx是一个高性能的HTTP和反向代理服务器,它内置了强大的负载均衡功能。以下是Nginx配置负载均衡的详细方法:
upstream backend {
server backend1.example.com;
server backend2.example.com;
server backend3.example.com;
}
server {
listen 80;
location / {
proxy_pass http://backend;
}
}
Nginx支持多种负载均衡算法:
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;
}
upstream backend {
server backend1.example.com max_fails=3 fail_timeout=30s;
server backend2.example.com max_fails=3 fail_timeout=30s;
}
upstream backend {
server backend1.example.com;
server backend2.example.com;
server backup.example.com backup;
}
upstream backend {
server backend1.example.com;
server backend2.example.com;
keepalive 32;
}
upstream backend {
sticky cookie srv_id expires=1h domain=.example.com path=/;
server backend1.example.com;
server backend2.example.com;
}
http {
upstream backend {
least_conn;
server backend1.example.com weight=3 max_fails=2 fail_timeout=30s;
server backend2.example.com weight=2 max_fails=2 fail_timeout=30s;
server backup.example.com 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_http_version 1.1;
proxy_set_header Connection "";
}
}
}
通过以上配置,Nginx可以有效地将客户端请求分发到多个后端服务器,提高系统的可用性和性能。