Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Servers, nginx and Docker

nginx 502 Bad Gateway in front of a Node.js app

Error502 Bad Gateway

Short 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.

  • Applies to nginx 1.26, Node.js 22, PM2 5, Ubuntu 24.04
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 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.log
  2. 2Match what you see, then jump to its fix

    1. 1connect() failed (111: Connection refused)The app is not running, or it crashed on startFix
    2. 2connect() failed (111: Connection refused) while the app is onlinenginx points at a different address than the app listens onFix
    3. 3upstream prematurely closed connection while reading response header (now and then, under load)Keep-alive timeouts race between nginx and Node.jsFix
    4. 4upstream sent too big header while reading response header from upstreamThe response headers are bigger than nginx's bufferFix
    5. 5(13: Permission denied) while connecting to upstreamnginx is not allowed to open the connectionFix

What does the error look like?

  • 502 Bad Gateway
  • connect() failed (111: Connection refused) while connecting to upstream
  • upstream prematurely closed connection while reading response header from upstream
  • upstream 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 --nostream

2Fix

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 save

3Verify

The app answers on its own port, without nginx in the way.

curl -I http://127.0.0.1:3000
Did this fix it?

Cause 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.com
Did this fix it?

Cause 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.log
Did this fix it?

Cause 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 -c

2Fix

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 nginx
Did this fix it?

Cause 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.sock

2Fix

Allow nginx to make outbound connections, or give the socket to a group nginx belongs to.

sudo setsebool -P httpd_can_network_connect 1

3Verify

Reload nginx and request the site again.

curl -I https://example.com
Did this fix it?

How 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:

Related fixes

Servers

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 fix

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.