Skip to content

/errors/nginx/502-bad-gateway

nginx: 502 Bad Gateway (connect() failed while connecting to upstream)

verified onenvironmentlocal · windows 10.0.26200 arm64 · GNU bash 5.3.15 (Git Bash) · nginx version: nginx/1.30.6updated
tool
nginx
versions
nginx 1.x
os
any

502 Bad Gateway from nginx means nginx itself works, but the upstream it proxies to (the address in proxy_pass, fastcgi_pass, uwsgi_pass) refused the connection, closed it, or sent a response nginx could not parse. The cause is always written in the nginx error log, in a line ending with while connecting to upstream or while reading response header from upstream. Start the backend or fix the address it is proxied to.

Reproduce it

nginx proxies to 127.0.0.1:4221, where nothing listens yet; then a Node backend starts on that port:

bash
mkdir -p logs temp
cat > nginx.conf <<'EOF'
pid logs/nginx.pid;
events {}
http {
  access_log off;
  server {
    listen 127.0.0.1:4222;
    location / { proxy_pass http://127.0.0.1:4221; }
  }
}
EOF
cat > backend.js <<'EOF'
require("http").createServer((req, res) => res.end("hello from the backend\n")).listen(4221, "127.0.0.1");
setTimeout(() => process.exit(0), 3000);
EOF
nginx -p . -c nginx.conf -e logs/error.log &
sleep 1
curl -s http://127.0.0.1:4222/ | grep '<title>'
echo "log lines 'while connecting to upstream': $(grep -c 'while connecting to upstream' logs/error.log)"
node backend.js &
sleep 1
curl -s http://127.0.0.1:4222/
nginx -p . -c nginx.conf -e logs/error.log -s stop

Output

<head><title>502 Bad Gateway</title></head>
log lines 'while connecting to upstream': 1
hello from the backend

Read the error log

bash
sudo tail -n 20 /var/log/nginx/error.log
Log message (Linux)Meaning
connect() failed (111: Connection refused) while connecting to upstreamnothing listens on that host and port
connect() to unix:/run/php/php-fpm.sock failed (2: No such file or directory)wrong socket path, or PHP-FPM is not running
connect() ... failed (13: Permission denied)socket permissions, or SELinux blocking the connection
upstream prematurely closed connection while reading response headerthe backend crashed or closed the connection mid-request
upstream sent too big header while reading response headerresponse headers (often cookies) exceed proxy_buffer_size
no live upstreams while connecting to upstreamevery server in the upstream block is marked as failed

Check the backend from the nginx host

bash
ss -ltnp | grep 3000                 # is anything listening on the port?
curl -v http://127.0.0.1:3000/       # does it answer without nginx?

Sources