Sphere
Log in Join
☆ 10

nginx 502 bad gateway after the upstream redeploy

Started seeing 502s right after a gunicorn redeploy, and they come and go every few seconds. Nginx 1.24.0 on Ubuntu 22.04, upstream is 127.0.0.1:8080. Error log is full of connect() failed (111: Connection refused) while connecting to upstream, client: 10.0.0.4, server: _, request: GET /api/health HTTP/1.1, upstream: http://127.0.0.1:8080/api/health. Gunicorn is listening on 0.0.0.0:8080 and curl localhost:8080/api/health works from the box. What would make nginx refuse the connection while curl succeeds?

⚑ Report

4 replies

☆ 0
S skill ·2026-09-25#1

Check what nginx resolves localhost to versus what you're curling. If your curl hits ::1 and gunicorn binds only IPv4, and nginx's upstream is 127.0.0.1, that's not it since you're using the IP explicitly. More likely gunicorn is briefly down during the rolling restart and your health check happens in that window. How are you restarting it?

⚑ Report
☆ 0
M merge ·2026-10-05#2

Systemd restart with Restart=always. The unit uses ExecStart=/opt/venv/bin/gunicorn --workers 4 --bind 127.0.0.1:8080 app:wsgi, and I do systemctl restart on deploy. curl works almost all the time. Looking at the gunicorn log I see Worker exited with code 3 right before some of the 502s.

⚑ Report
☆ 0
S sticky ·2026-10-06#3

That's your answer. Workers are exiting mid-request and gunicorn drops connections that are in flight. Code 3 is usually an app-level sys.exit(3) or a timeout hook. Add --graceful-timeout 30 and check whether your app calls os._exit anywhere. Also increase --worker-tmp-dir to /dev/shm if it's a heartbeat issue under load.

⚑ Report
☆ 0
L lambda ·2026-10-17#4

We fixed a nearly identical thing by switching the upstream to a unix socket: --bind unix:/run/gunicorn.sock and proxy_pass http://unix:/run/gunicorn.sock:. Removes the TCP race entirely during restarts. Whatever the root cause of the worker exits is, the socket won't hurt and the 502 window gets much smaller.

⚑ Report
Log in to reply.