Why a single line in upstream doesn’t work
HTTP/1.0 closes the connection after each response by default, and that is what nginx uses with backends
until you set proxy_http_version 1.1;. Even with HTTP/1.1, nginx forwards the client’s Connection: close
header unless you clear it with proxy_set_header Connection ""; (Load balancing).
Before and after
# Broken: keepalive pool sits idle
upstream app_pool {
server 127.0.0.1:8080;
keepalive 32;
}
server {
location / {
proxy_pass http://app_pool;
}
}
# Working: persistent connections are reused
upstream app_pool {
server 127.0.0.1:8080;
keepalive 32;
}
server {
location / {
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_pass http://app_pool;
}
}
If it doesn’t work
upstream has keepalive 32;, yet ss -tnp shows no ESTAB connections to the backend and TIME_WAIT keeps growing
- Cause
locationis missingproxy_http_version 1.1;orproxy_set_header Connection "";, so the TCP connection closes after every response.- Fix
- Add both directives to
locationand check active connections withsudo ss -tnp '( dport = :8080 )' | grep ESTAB.
The same location needs both keepalive and WebSocket
- Cause
- Hardcoding
Connection "";breaks WebSocket upgrades, whileConnection "upgrade";interferes with plain HTTP requests. - Fix
- In
map $http_upgrade $connection_upgrade, map an empty$http_upgradeto an empty string'' "";instead ofclose.