upstream backend {
server backend1.example.com weight=5;
server backend2.example.com max_fails=3 fail_timeout=30s;
# 主动健康检查
health_check interval=5s uri=/health_check;
health_check_timeout 3s;
health_check_status 200;
}
vrrp_script chk_nginx {
script "pidof nginx"
interval 2
weight 2
}
vrrp_instance VI_1 {
state MASTER
interface eth0
virtual_router_id 51
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
track_script {
chk_nginx
}
virtual_ipaddress {
192.168.1.100
}
}
location /api {
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 2s;
proxy_read_timeout 5s;
proxy_send_timeout 3s;
}
# 限流配置
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=100r/s;
location /api {
limit_req zone=api_limit burst=50 nodelay;
# 熔断降级
error_page 502 503 504 = @fallback;
}
location @fallback {
proxy_pass http://fallback_server;
add_header X-Cache-Status "Fallback";
}
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m inactive=60m;
location / {
proxy_cache my_cache;
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
}
# 金丝雀发布配置
map $cookie_canary $backend {
default "production";
"true" "canary";
}
upstream production {
server 10.0.0.1:8080;
server 10.0.0.2:8080;
}
upstream canary {
server 10.0.1.1:8080;
}
server {
location / {
proxy_pass http://$backend;
}
}
通过以上设计原则和技术实现,可以构建出高可用、高容错的Nginx服务架构,确保业务连续性并提升用户体验。