nginx 502 Bad Gateway in front of a Node.js app
502 Bad GatewayShort answer
A 502 means nginx reached for your Node.js app and got nothing usable back. Open the nginx error log first: it names the cause. In practice it is one of five things: the app is down, nginx points at the wrong address, keep-alive timeouts race, the response headers are too big, or nginx may not open the connection.
Fix it fast
1Find out which cause you have
Read the last lines of the nginx error log. The message after the timestamp tells you which cause below applies.
sudo tail -n 30 /var/log/nginx/error.log2Match what you see, then jump to its fix
- 1
connect() failed (111: Connection refused)The app is not running, or it crashed on startFix - 2
connect() failed (111: Connection refused) while the app is onlinenginx points at a different address than the app listens onFix - 3
upstream prematurely closed connection while reading response header (now and then, under load)Keep-alive timeouts race between nginx and Node.jsFix - 4
upstream sent too big header while reading response header from upstreamThe response headers are bigger than nginx's bufferFix - 5
(13: Permission denied) while connecting to upstreamnginx is not allowed to open the connectionFix
- 1
What does the error look like?
502 Bad Gatewayconnect() failed (111: Connection refused) while connecting to upstreamupstream prematurely closed connection while reading response header from upstreamupstream sent too big header while reading response header from upstream
Cause 1 of 5
The app is not running, or it crashed on start
1Check
Ask PM2 whether the process is online and read its last log lines.
pm2 status
pm2 logs my-app --lines 50 --nostream2Fix
Fix the error the log shows (a missing environment variable and a failed database connection are the usual ones), then restart and save the process list so it comes back after a reboot.
pm2 restart my-app --update-env
pm2 save3Verify
The app answers on its own port, without nginx in the way.
curl -I http://127.0.0.1:3000Cause 2 of 5
nginx points at a different address than the app listens on
1Check
Compare the address in proxy_pass with what Node.js actually listens on. Since Node.js 17, localhost can resolve to the IPv6 address ::1 first, so an app bound to ::1 refuses nginx's 127.0.0.1.
sudo ss -ltnp | grep node
grep -R "proxy_pass" /etc/nginx/sites-enabled/2Fix
Use one explicit address on both sides: bind the app to 127.0.0.1 and point proxy_pass at the same address and port.
// server.js
app.listen(3000, '127.0.0.1');
# nginx site config
location / {
proxy_pass http://127.0.0.1:3000;
}3Verify
Test the config, reload nginx and request the site through nginx.
sudo nginx -t && sudo systemctl reload nginx
curl -I https://example.comCause 3 of 5
Keep-alive timeouts race between nginx and Node.js
1Check
This only appears when nginx reuses upstream connections (keepalive in the upstream block). Node.js closes idle connections after 5 seconds by default; if nginx keeps them longer, it sometimes sends a request down a socket Node.js is closing.
grep -R -n "keepalive" /etc/nginx/2Fix
Make Node.js keep idle connections open longer than nginx does, and set headersTimeout a little above keepAliveTimeout.
const server = app.listen(3000, '127.0.0.1');
server.keepAliveTimeout = 65000; // longer than nginx's upstream keepalive_timeout (60s default)
server.headersTimeout = 66000;3Verify
Run a short load test and watch the error log stay quiet.
npx autocannon -c 50 -d 60 https://example.com/health
sudo tail -f /var/log/nginx/error.logCause 4 of 5
The response headers are bigger than nginx's buffer
1Check
Large cookies, long JWTs or many Set-Cookie headers overflow the default 4k or 8k proxy buffer. The 502 then shows only for logged-in users or on some routes.
curl -s -D - -o /dev/null http://127.0.0.1:3000/login | wc -c2Fix
Raise the proxy buffers for that site, and if you can, trim what goes into cookies.
location / {
proxy_pass http://127.0.0.1:3000;
proxy_buffer_size 16k;
proxy_buffers 8 16k;
proxy_busy_buffers_size 32k;
}3Verify
Reload nginx and repeat the request that failed, signed in.
sudo nginx -t && sudo systemctl reload nginxCause 5 of 5
nginx is not allowed to open the connection
1Check
On RHEL, Rocky or Alma Linux, SELinux blocks nginx from opening network connections by default. With a Unix socket, the socket file's permissions can block it too.
getenforce
ls -l /run/my-app.sock2Fix
Allow nginx to make outbound connections, or give the socket to a group nginx belongs to.
sudo setsebool -P httpd_can_network_connect 13Verify
Reload nginx and request the site again.
curl -I https://example.comHow do I stop it coming back?
- Add a /health route and an uptime check that calls it every minute, so a crash is found before a customer finds it.
- Run the app under PM2 or systemd with automatic restart, and save the process list.
- Keep one explicit address (127.0.0.1 and a port) in both the app and nginx.
- Log the upstream response time in nginx so slow routes show up before they become errors.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
- TaxiDexMy own multi-tenant taxi dispatch SaaS: API, dispatcher portal, driver and passenger apps, and the servers underneath.
- WorkforceA field app, an admin console and a self-hosted Node.js server for push and reconciliation.
- QistLockA NestJS and React SaaS driving an Android Device Owner agent that locks financed phones when payments lapse.
Related fixes
Servers
Azure App Service on Linux restarts the container and the site never starts
The container restarts again and again and the site returns an application error
App Service sends a warmup request to the container and restarts it if no HTTP answer comes back in time.
5 causes, each with a fixServers
nginx gives up waiting for the app and returns 504
upstream timed out (110: Connection timed out) while reading response header from upstream
nginx returns 504 when the app behind it takes the request but sends nothing back within proxy_read_timeout (60 seconds by default), or when the connection cannot be opened in time.
5 causes, each with a fixServers
Pages load unstyled because /_next/static files return 404 behind nginx
GET https://example.com/_next/static/chunks/main.js 404 (Not Found)
The browser asks for /_next/static/..
3 causes, each with a fixServers
The shell cannot find pm2 after you installed it
bash: pm2: command not found
The shell found no pm2 file in any folder of PATH.
3 causes, each with a fixServers
A Let's Encrypt certificate did not renew with Certbot
Type: connection ... Timeout during connect (likely firewall problem)
Run sudo certbot renew --dry-run and read the Type and Detail lines.
6 causes, each with a fixServers
curl cannot connect to port 80 or 443 on a server running nginx
CURLE_COULDNT_CONNECT (7): Failed to connect() to host or proxy
Exit code 7 means the TCP connection itself failed, before any HTTP happened.
3 causes, each with a fix