brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: nginx keepalive in an upstream block reuses connections to your backend

Nginx
~/tips/tip-nginx-upstream-keepalive

upstream app_backend {

Keeps a few connections from nginx to the backend open for reuse instead of reconnecting per request.

On older nginx versions a reverse proxy opens a fresh connection to the backend for every single request and closes it again afterwards. For an app on the same machine that costs little, but with lots of small API calls, or a backend somewhere else on the network, I’d rather keep a few connections open and reuse them.

upstream app_backend {
    server 192.168.1.20:8080;
    keepalive 16;
}

server {
    location / {
        proxy_pass http://app_backend;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
    }
}

keepalive 16 lets each worker process keep up to 16 idle connections to the servers in this upstream. The two lines in the location are what make it work on older versions: the proxy talks HTTP/1.0 to the backend by default there, and it sends Connection: close, so the backend hangs up after every answer. HTTP/1.1 and an empty Connection header fix both.

Whether you need this depends on your version, so check nginx -v first. Since nginx 1.29.7 upstream keepalive is on by default, with 32 connections per worker, and HTTP/1.1 is the default towards the backend. Ubuntu 24.04 ships nginx 1.24, though, and there none of this happens until you write it down. The extra lines do no harm on a new version, so I’d keep them in the config anyway.

The caveat is in the number. It is not a limit on how many connections nginx opens to the backend, only how many idle ones it keeps around per worker. With four workers and keepalive 16 that can be 64 connections sitting open, so keep it small for a backend that can only handle a few at a time.

It only works with a named upstream block. A proxy_pass http://192.168.1.20:8080 with the address written straight in has no place for the directive.

Further reading: ngx_http_upstream_module: keepalive, ngx_http_proxy_module: proxy_http_version

Going deeper: Guide: fix a 502 Bad Gateway in Nginx Proxy Manager, with a checklist that finds the cause

More Nginx tips sudo certbot --nginx -d example.com -d www.example.com /data/nginx/custom/server_redirect.conf map $http_upgrade $connection_upgrade { proxy_intercept_errors on; proxy_redirect http://localhost:3000/ /app/; All Nginx tips (50) All topics

Link