Skip to main content
5xx Server Error

502 Bad Gateway

The server, while acting as a gateway or proxy, received an invalid response from the upstream server it accessed.

Meaning & Description

The 502 Bad Gateway status code indicates that a server acting as a gateway or proxy received an invalid or unexpected response from an inbound server it accessed while attempting to fulfill the request. This usually means the proxy server is working fine, but the backend application server it is talking to has crashed, returned malformed HTTP, or abruptly dropped the connection.

Common Causes

  • The upstream backend service (e.g., PM2, Docker container) is down or crashed.
  • The backend service is returning a malformed HTTP response that the proxy cannot parse.
  • The proxy is trying to communicate over an invalid protocol or port (e.g., trying to speak HTTP to an HTTPS port).
  • Firewall rules blocking traffic between the reverse proxy and the backend server.

How to fix a 502 error

  1. Check if the upstream application server (Node.js, Python, Java, etc.) is running and listening on the expected port.
  2. Inspect the proxy logs (Nginx error.log, HAProxy logs, or Cloudflare dashboard) to see exactly why it rejected the upstream response.
  3. Verify network connectivity and firewall rules between the proxy server and the backend server.
  4. Ensure the backend is returning valid HTTP headers. A script that echoes text without HTTP headers will cause a 502 at the proxy.

Browser & SEO Behaviour

Browser Behavior

Displays a generic 502 error page or a customized page provided by the CDN (like Cloudflare’s "Host Error" screen).

SEO Impact

Severe negative impact if it persists. Search engines cannot crawl your content. A brief 502 during a deployment is usually fine, but hours of 502s will result in de-indexing.

CDN Behavior

CDNs actively intercept this error. Many will present a stylized, branded error page to the user rather than passing raw JSON. They do not cache the 502 itself.

Code Examples

HTTP
HTTP/1.1 502 Bad Gateway
Server: nginx
Content-Type: text/html

<html>
<body>
<h1>502 Bad Gateway</h1>
</body>
</html>
Node.js (http-proxy)
const httpProxy = require("http-proxy");
const proxy = httpProxy.createProxyServer({});

proxy.on("error", function (err, req, res) {
  res.writeHead(502, {
    "Content-Type": "application/json"
  });
  res.end(JSON.stringify({ error: "Bad Gateway", message: "Upstream server failed." }));
});

// Starts a proxy listening on 8080 routing to a non-existent port 9000
require("http").createServer((req, res) => {
  proxy.web(req, res, { target: "http://localhost:9000" });
}).listen(8080);
Go (httputil)
package main

import (
	"net/http"
	"net/http/httputil"
	"net/url"
)

func main() {
	target, _ := url.Parse("http://localhost:9999") // Backend that is down
	proxy := httputil.NewSingleHostReverseProxy(target)
	
	proxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) {
		w.WriteHeader(http.StatusBadGateway)
		w.Write([]byte("502 Bad Gateway: Upstream failure"))
	}
	
	http.ListenAndServe(":8080", proxy)
}
Nginx Config
# Common Nginx configuration that results in 502 if upstream is down
upstream backend {
    server 127.0.0.1:3000;
}

server {
    listen 80;
    location / {
        proxy_pass http://backend;
        # 502 occurs here if localhost:3000 is not responding
    }
}

Raw HTTP Response Example

HTTP Response
HTTP/1.1 502 Bad Gateway
Date: Wed, 21 Oct 2026 07:28:00 GMT
Server: cloudflare
Content-Type: text/html

<html><body><h1>502 Bad Gateway</h1></body></html>

Real-world Examples

Cloudflare: Displays a "502 Bad Gateway" page with an illustration of a cloud and a server, indicating Cloudflare could not connect to the origin server.
Nginx: The default error when an Nginx proxy_pass directive fails to get a valid response from the downstream application.
AWS Application Load Balancer: Returns a 502 if the registered EC2 target or ECS container closes the connection with a TCP RST or sends malformed HTTP headers.

Frequently Asked Questions

How do I fix a 502 Bad Gateway error?

If you are a visitor, clear your cache and refresh, but it is usually the website’s fault. If you are a developer, check if your application server (like Node or Python) has crashed or is listening on the wrong port.

What is the difference between 502 Bad Gateway and 504 Gateway Timeout?

502 means the proxy connected to the backend but received an invalid or malformed response (or the connection dropped). 504 means the proxy connected to the backend, but the backend took too long to respond at all.

Why does Cloudflare show a 502 error?

Cloudflare acts as a reverse proxy. A 502 means Cloudflare is working perfectly, but the server hosting your actual website is down, misconfigured, or blocking Cloudflare’s IP addresses.

Can a 502 error be caused by a bad DNS record?

Usually not directly. If DNS is completely wrong, the proxy will fail to resolve the IP and might return a 502 or 503, but typically a 502 means an IP was reached, but the server on that IP failed to speak proper HTTP.

Did You Know?

A 502 error almost always points a finger directly at the communication bridge between two servers, rather than the client or the ultimate database.

Many 502 errors happen silently during CI/CD deployments when a proxy tries to route traffic to a container that is still spinning up.

Developer Tips

  • To avoid 502 errors during deployments, implement zero-downtime deployments. Ensure your proxy only routes traffic to the new container after it passes a health check.
  • If you write custom proxy software, always sanitize the upstream response headers before forwarding them to the client to prevent malformed headers from breaking the proxy itself.
  • Use tools like Datadog or Prometheus to track 502 error rates on your load balancers. A sudden spike usually means a backend service is crash-looping.

Interview Questions

These are questions you might face in a backend or API design interview that touch on HTTP 502.

If you see a 502 Bad Gateway from Nginx, where would you look first to solve it?

I would look at the Nginx error log to confirm which upstream server failed, then I would check the application logs (e.g., PM2, Docker) for that specific backend service to see if it crashed or failed to start.

Explain the difference between a 500, 502, and 503 error.

500 is a generic application crash. 502 means a proxy received a bad response from the application. 503 means the application or proxy is intentionally overloaded or down for maintenance.

Common Interview Mistakes

  • Saying that a 502 error means the database is down. While a down database might crash the application, the 502 itself comes from the proxy failing to talk to the application layer.
  • Assuming the client can fix a 502 by changing their request payload. A 502 is strictly an infrastructure routing issue on the server side.