← Back to Chapters

502 Bad Gateway

? 502 Bad Gateway

? Quick Overview

The 502 Bad Gateway error is an HTTP status code indicating that a server acting as a gateway or proxy received an invalid response from an upstream server. It commonly appears in web applications using reverse proxies, load balancers, or microservice architectures.

? Key Concepts

  • Occurs between Gateway and Upstream Server
  • Client request is valid
  • Failure happens server-to-server
  • Often temporary but critical in production

? Syntax / Theory

In HTTP communication, a gateway (like Nginx or Apache) forwards client requests to backend services. If the backend crashes, times out, or returns malformed data, the gateway responds with:

HTTP Response

Status Code: 502
Meaning: Bad Gateway

? Code Example(s)

? View Code Example
// Nginx configuration example that may trigger 502 if backend is down
server {
listen 80;
location / {
proxy_pass http://127.0.0.1:3000;
}
}

? Live Output / Explanation

What Happens?

If the Node.js app on port 3000 is stopped or crashes, Nginx cannot get a valid response and shows 502 Bad Gateway to the user.

? Interactive Diagram

Client Gateway Upstream

?️ Interactive Simulation

Toggle the server status and send a request to see the Gateway's response.

Client
Gateway
Upstream
Waiting for request...

? Use Cases

  • Reverse proxy setups (Nginx, Apache)
  • Microservices communication
  • API gateways
  • Load-balanced architectures

? Tips & Best Practices

  • Check backend server logs first
  • Ensure correct ports and IPs
  • Increase proxy timeout if needed
  • Restart crashed services

?️ Try It Yourself

  • Stop a backend service and observe 502
  • Fix the service and reload
  • Change proxy_pass to invalid port
  • Monitor logs in real-time