Nginx提供了多种机制来实现HTTP请求的重试和故障转移功能,主要通过upstream模块和proxy模块的相关指令来实现。以下是详细的配置方法:
upstream backend {
server backend1.example.com;
server backend2.example.com;
server backend3.example.com backup; # 备用服务器
}
server {
location / {
proxy_pass http://backend;
proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
proxy_next_upstream_tries 3;
proxy_next_upstream_timeout 10s;
}
}
proxy_next_upstream: 指定在什么情况下将请求转发到下一个服务器
error
(连接错误)、timeout
(超时)、invalid_header
(无效响应头)、http_500
(500错误)等error timeout
proxy_next_upstream_tries: 最大重试次数
proxy_next_upstream_timeout: 重试超时时间
upstream backend {
server backend1.example.com max_fails=3 fail_timeout=30s;
server backend2.example.com max_fails=3 fail_timeout=30s;
# 主动健康检查(商业版功能)
# health_check interval=5s fails=3 passes=2 uri=/health;
}
upstream backend {
server backend1.example.com weight=5;
server backend2.example.com weight=3;
server backup.example.com backup;
}
upstream backend {
least_conn; # 最少连接算法
# ip_hash; # IP哈希算法
# hash $request_uri consistent; # 一致性哈希
server backend1.example.com;
server backend2.example.com;
}
upstream backend {
server backend1.example.com slow_start=30s;
server backend2.example.com slow_start=30s;
}
http {
upstream backend {
# 负载均衡策略
least_conn;
# 后端服务器
server backend1.example.com max_fails=3 fail_timeout=30s weight=5;
server backend2.example.com max_fails=3 fail_timeout=30s weight=3;
server backup1.example.com backup;
server backup2.example.com backup;
# 健康检查(商业版)
# health_check interval=5s fails=3 passes=2 uri=/health;
}
server {
listen 80;
location / {
proxy_pass http://backend;
# 故障转移设置
proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
proxy_next_upstream_tries 3;
proxy_next_upstream_timeout 10s;
# 超时设置
proxy_connect_timeout 5s;
proxy_read_timeout 60s;
proxy_send_timeout 60s;
# 其他代理设置
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
}
nginx_upstream_check_module
通过合理配置这些参数,可以构建一个具有良好容错能力的反向代理服务。