by nodesocket · 10y ago · 0 comments
Sorry for the long code block below, but it is a full working example that has automatic health checks (adds and removes backends automatically) and a dynamic backend configuration that is persisted to a state file.
http {
proxy_next_upstream error timeout http_502 http_504;
match statusok {
status 200;
body ~ "200 OK";
}
upstream backend {
state /etc/nginx/backend-state/backends;
zone backend 256k;
keepalive 20;
}
}
server {
# dynamic upstream
location = /upstream_conf {
upstream_conf;
allow 127.0.0.1;
deny all;
}
location / {
proxy_connect_timeout 15s;
proxy_http_version 1.1;
proxy_set_header Connection "";
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_set_header X-Forwarded-Proto $scheme;
proxy_pass http://backend;
}
# health check
location /internal-health-check {
internal;
proxy_connect_timeout 15s;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_pass http://backend;
health_check interval=3s fails=3 passes=5 uri=/health match=statusok;
}
}
[1] - https://nginx.org/en/docs/http/ngx_http_upstream_conf_module...[2] - http://nginx.org/en/docs/http/ngx_http_upstream_module.html#... [3] - http://nginx.org/en/docs/http/ngx_http_upstream_module.html#...
# add a backend
curl http://127.0.0.1/upstream_conf?add=&upstream=backend&server=10.0.0.1:8000
# remove a backend
curl http://127.0.0.1/upstream_conf?remove=&upstream=backend&id=1
[1] - https://www.nginx.com/blog/dynamic-reconfiguration-with-ngin...A demo of this can be found here[0]
0: https://github.com/nginxinc/NGINX-Demos/tree/master/consul-d...