Skip to content
Loopedin Labs

502 Bad Gateway (nginx and Ingress)

Users see a gateway error page. Find out which piece actually failed.

Mini Rush · practice

Three questions before you read

Guessing first makes the answers stick. No sign-in.

The error log names the cause of nearly every 502. Here's how to read it.

What it means

nginx (or ingress-nginx, or a cloud load balancer) accepted the client's request and passed it to an upstream, but couldn't get a valid response back. nginx is running. The problem is the hop behind it.

Keep the nearby codes apart:

Codenginx's view
502connecting to the upstream failed, or its response was broken or invalid
503ingress-nginx: the Service has no endpoints; nginx: a limit_req or limit_conn rejection
504the upstream accepted the connection, then didn't answer in time

Read the error log first

nginx writes the reason for every 502 to the error log. The access log only shows the status code.

sudo tail -n 50 /var/log/nginx/error.log
kubectl logs -n ingress-nginx deploy/ingress-nginx-controller | grep -E 'upstream|connect\(\)'
Log fragmentMeaning
connect() failed (111: Connection refused)nothing listening at the upstream address or port
connect() to unix:/run/php/php-fpm.sock failed (13: Permission denied)socket permissions, or SELinux
upstream prematurely closed connectionthe app crashed or closed the connection mid-response
upstream sent too big headerthe response headers don't fit in proxy_buffer_size
no live upstreamsevery server in the upstream block is marked failed

Check the upstream directly

From the nginx host or pod, skip nginx and test the upstream:

curl -v http://127.0.0.1:8080/health
ss -ltnp | grep 8080

In Kubernetes, follow the chain from Ingress to Service to pod:

kubectl describe ingress web
kubectl get svc web -o jsonpath='{.spec.ports}'
kubectl get endpointslices -l kubernetes.io/service-name=web
kubectl get pod -l app=web -o jsonpath='{.items[0].spec.containers[0].ports}'

On RHEL-family hosts, if nginx can't reach a TCP upstream and the log says 13: Permission denied, SELinux is blocking it:

sudo setsebool -P httpd_can_network_connect 1

Usual causes

  • The app is down, restarting, or OOMKilled, which shows up as 502s in bursts.
  • proxy_pass or the Service targetPort points at the wrong port.
  • The app is bound to 127.0.0.1 while nginx connects to the pod or host IP.
  • Protocol mismatch: nginx sends plain HTTP to an HTTPS backend, or the reverse (ingress-nginx's backend-protocol annotation).
  • The upstream's keep-alive timeout is shorter than the proxy's.

Common wrong fix

Raising proxy_read_timeout or proxy_connect_timeout. Timeouts produce 504s, not 502s. A 502 means the connection was refused, reset, or got a bad response, and waiting longer doesn't change any of those. Restarting nginx is the other reflex. It clears the error for a minute, if at all, because the upstream is still broken. Read the error log line first; it almost always names the cause.