Skip to content

Digital marketing

502 error – what it means and how to fix it?

Read the articleQuestions and answers

Article cover: 502 error – what it means and how to fix it?
Error 502 (Bad Gateway) appears when a proxy server does not receive a valid response from the “upstream” server (application or origin server). For the user, it looks like a site outage, but in practice it is most often an issue with communication between layers: a CDN/proxy/load balancer and the backend. In this guide, I’ll show you how to determine where 502 comes from and what it usually means depending on the architecture (e.g. Nginx, Cloudflare, ALB, Kubernetes). You’ll also get concrete pointers on what data to collect so the diagnosis is quick and not based on guesswork. When 502 occurs only for you, you’ll start with simple client-side tests, and if it is global, you’ll focus on logs and service health. Read on to move from symptoms to cause and take the right path to fixing it.

What does error 502 mean and how do you recognise it?

Error 502 means that the proxy server (e.g. reverse proxy, CDN, load balancer) was unable to process or correctly interpret the response from the backend (“upstream”). The role of the “gateway” may be played by Nginx/Apache as a proxy, Cloudflare, AWS ALB/ELB or an Ingress in Kubernetes, and the “upstream” may be, for example, PHP-FPM, Node.js, Gunicorn/Uvicorn, Tomcat or an API service over HTTP/TCP. Unlike 500 (application error), 503 (service unavailable) and 504 (timeout), 502 more often suggests a “faulty” response or a broken connection between layers. This applies not only to websites, but also to APIs and mobile applications, where in tools such as curl/Postman you will see, for example,

HTTP/1.1 502 Bad Gateway

.

The source of 502 can often be inferred from the error screen or from response headers visible in DevTools (Network). In the headers, look for fields such as `server`, `via`, `cf-ray` or `x-cache`, because they usually indicate whether the error is being generated by Nginx on the origin, a CDN or a load balancer. In proxy logs, administrators often encounter messages such as `connect() failed (111: Connection refused)` or `upstream prematurely closed connection`, which point to a problem connecting to the upstream or an abrupt termination of the response. It also happens that refreshing (F5) helps for a moment, which can be a clue towards a backend process restart or fluctuations in load. Before you move on to fixing it, it is worth noting the time, the full URL, whether the problem affects the whole domain or only one subpage, and whether it occurs on different networks (Wi‑Fi/LTE).

Error 502 What does error 502 mean and how do you recognise it?
  1. 01Proxy gatewayProcesses requests, passes them on.
  2. 02Faulty responseIncorrect interpretation of the response.
  3. 03Broken connectionNo stability between layers.
  4. 04Identify the sourceCheck the error, DevTools, logs.

The key is to understand that the problem lies in communication between the proxy server and the target server, not necessarily in the application itself.

What are the most common causes of error 502 on the server side?

The most common server-side causes of 502 come down to a situation where the upstream is not working, is not listening on the port, or breaks the connection while generating the response. If the backend has crashed (e.g. stopped PHP-FPM or the application process), the proxy will not establish a connection to the upstream and will return 502, often with “connection refused” or “no live upstreams” errors. The problem usually worsens under CPU/RAM pressure or when processes are killed by OOM (Out Of Memory), when the backend starts resetting TCP sessions. In PHP-FPM, a typical source of 502 is a lack of available processes (e.g. `pm.max_children`) or timeouts, so subsequent requests have no one to handle them. There are also application errors that terminate the connection before a valid HTTP response is sent, and the proxy reads this as an invalid response.

TTFB (Time To First Byte) graphic with a three-colour bar: green up to 800 ms, orange up to 1800 ms, red above
Diagram TTFB is the time to the first byte of the server response: roughly good up to 0.8 s, poor above 1.8 s. Source: web.dev (Google), CC BY 4.0

502 can also be a consequence of configuration errors and dependencies between layers, even if the application is “theoretically” working. An incorrectly configured `proxy_pass`/`fastcgi_pass` (wrong port, socket or host) can return an immediate 502 after changes, even though the upstream is running. TLS problems between the gateway and the upstream (e.g. handshake error, mismatched SNI or a missing full certificate chain after an update) can also end in 502 rather than a clear message. In some deployments, 502 appears when layer limits are hit, for example overly large headers (bloated cookies) or responses that exceed proxy buffer limits. Less often, network issues are to blame, such as a firewall blocking connections from the gateway to the backend or NAT/conntrack exhaustion under heavy traffic, which causes intermittent connection drops.

Typical scenarios for error 502 in different architectures

Error 502 most often occurs in architectures where traffic passes through an intermediary layer (CDN, reverse proxy, load balancer) before reaching the application. On Cloudflare or another CDN, 502 may result from a problem on the origin side, the CDN↔origin link, or WAF rules, and the error screen is sometimes accompanied by a Ray ID identifier. In the case of Nginx as a reverse proxy, 502 usually means that PHP-FPM/Node/Gunicorn did not respond or reset the connection, which often happens in applications such as WordPress, Laravel or Django. If 502 appears at the CDN layer, start by determining whether the problem concerns the origin, the connection to the origin or security rules (WAF/rate limiting), because each of these causes requires a different direction of remediation.

In cloud and distributed environments, 502 is sometimes a “symptom” of issues with target health or routing. In AWS ALB/ELB, 502 may result from an instance in the Target Group responding incorrectly, a TLS issue appearing, or the health check being configured incorrectly (it is worth checking Target Group → Health and the ALB logs). In Kubernetes, 502 often means there are no healthy endpoints (pods not ready) or traffic is being sent to the wrong port, which can be quickly confirmed with `kubectl get endpoints`, `kubectl describe ingress` and the Ingress controller logs. In microservices architectures and on API Gateway, 502 also appears when a specific service fails or a route has overly aggressive timeouts, so the error affects only selected endpoints.

In practice, 502 can also occur in “near-configuration” scenarios that do not resemble a classic application outage. After renewing certificates or changing TLS settings, a handshake error between the gateway and the upstream is possible (for example, mismatched SNI or a missing full chain), which can be mapped to 502. During migrations, common causes turn out to be DNS and routing problems, when the gateway resolves the upstream to the wrong IP (for example, due to an old A/CNAME record and a high TTL). If 502 appears only after logging in or only on selected views, check header size limits (for example, oversized cookies) and caching in the proxy, because the “public” page may work correctly despite an error on paths with more headers.

Technology Typical scenarios in which error 502 occurs in different architectures
  1. 01Intermediary layerCDN, reverse proxy, load balancer.
  2. 02Error on CDN / CloudflareOrigin, link, WAF (with identifier).
  3. 03Error on Nginx / reverse proxyApplication not responding (PHP/Node).
  4. 04CDN layer diagnosisCheck the origin, connection, rules.

The key to resolving error 502 is to precisely identify in which layer of the infrastructure – CDN, proxy or application – the communication problem occurred.

Diagnosing error 502: tools and steps to resolve the problem

The best way to start diagnosing error 502 is by establishing whether the problem affects the entire domain or only a specific path, because that immediately narrows the search area. If the error occurs only on one endpoint (for example, an upload or a specific API call), the suspicion usually falls on a size limit, timeout or a single upstream. If it affects the whole domain, it is more often an upstream outage or a gateway configuration issue. To quickly identify the layer returning 502, use `curl -v` (or `curl -i`) and analyse the response headers. Headers such as `server`, `via`, `cf-ray`, `x-amz-cf-id`, `x-served-by` or `x-cache` are a practical clue as to whether 502 comes from the CDN, load balancer or a proxy on the origin.

  • Reproduce the error in the browser, and in DevTools (Network) save a HAR file to check timing, redirects and whether 502 affects a single request (for example, XHR) or the whole page.
  • Verify DNS and the route: `dig`/`nslookup` will show which IP the domain points to, and `traceroute`/`tracert` will help if you suspect routing issues or blocks along the way.
  • On the server, inspect the logs in real time (for example, `tail -f /var/log/nginx/error.log` and the application logs) and look out for phrases such as `upstream`, `connect() failed`, `recv() failed`, `prematurely closed connection`.
  • Confirm the status of services and ports: `systemctl status …` and `ss -ltnp | grep :PORT` (or socket verification) will indicate whether the upstream is working and whether it is actually listening.
  • Test the upstream directly (for example, `curl http://127.0.0.1:PORT/health` or via a unix socket), to separate the problem on the application side from an error in the proxy configuration.

If after testing there is still no clear cause, the key becomes correlating events with load and the behaviour of intermediary layers. Check the metrics (for example, in Grafana/Prometheus) or at least `top`/`iostat` to see whether 502 occurs alongside spikes in CPU, RAM, IO or the number of connections, because this often suggests worker and resource limits. In environments with a CDN/WAF/load balancer, it is also worth comparing the time of the error with logs and events from the protection layers (Firewall Events, Rate Limiting), because blocks and thresholds can redirect traffic in a way that only becomes visible in the data. Once you have collected a coherent set of information. URL, time, headers and identifiers (for example, Ray ID). it is much easier to link 502 to a specific log entry and reach the correct fix faster.

What actions should be taken to prevent error 502 from recurring?

To reduce the risk of error 502 (Bad Gateway) returning, it is worth implementing monitoring, sensible health checks and a predictable deployment process, so that the gateway (proxy/CDN/LB) does not send traffic to an unready or overloaded upstream. It is important to catch increases in 5xx and latency before they turn into a wave of 502s for users or API clients. It also helps to collect data that allows you to quickly correlate a single request with logs across all layers. This way, instead of guessing, you will more quickly establish whether the problem concerns backend availability, its performance or the configuration of intermediaries.

The most practical step is often external availability monitoring with alerts on rising 5xx errors and tests of key journeys (e.g. login, checkout, API endpoint), because the homepage itself may work even when critical functions are returning 502. At the same time, collect backend and proxy metrics. the number of 502/5xx errors, p95/p99 latency, the number of active connections, memory usage and worker queues. so you can see trends and links with traffic. If 502 appears during spikes, implement autoscaling (e.g. HPA in Kubernetes or ASG in AWS) and proper CPU/RAM limits/requests, because without a resource buffer the backend starts dropping connections and the gateway reports 502. In addition, keep “expensive” endpoints in check through caching and traffic limiting (e.g. `limit_req` in Nginx), so you avoid a situation where a single spike in requests can destabilise the upstream.

Deployment processes and observability between layers also affect 502 stability, because many incidents appear during restarts and rollouts. Deploy with graceful shutdown and use blue/green or canary strategies so that new instances are fully ready before they take over traffic, and any potential problem affects only a small percentage of requests. In centralised logging (e.g. ELK/Elastic, Loki), it is a good idea to pass the request identifier (e.g. `X-Request-ID`) through the proxy to the application, which makes it much easier to track down the source of 502 in distributed systems. Complement this with a concise runbook and incident checklist (logs, service status checks, how to bypass the CDN, rollback, critical limits) to shorten recovery time under increased stress.

Infrastructure management What actions should be taken to prevent the 502 error from recurring?
  1. 01Early detectionMonitor the rise in 5xx errors.
  2. 02Efficient health checksRoute traffic only to ready services.
  3. 03Safe processesPlan and test changes.
  4. 04Rapid diagnosisAnalyse logs across layers.

The key is proactive action: monitoring, testing and better data visibility to avoid a wave of 502 errors.

The role of CDN, WAF and load balancers in generating 502 errors

CDN, WAF and load balancers can return 502 when the intermediary layer does not receive a correct response from the origin or backend, or when security and routing rules interrupt communication. In practice, 502 is often the result of a combination of: an unstable origin, badly configured health checks, TLS issues between layers, or WAF filters that alter the flow of requests. This matters because diagnosis and remediation depend on whether the 502 is “generated” on the CDN/WAF/LB, or only on a proxy close to the application. In cloud environments, it is often also crucial whether the load balancer can see any healthy targets and how it interprets the application’s “health” status.

Diagram: a browser with cache sends a request with the If-None-Match header, the server responds with code 304 and cache headers
Diagram The browser asks the server whether the file has changed (If-None-Match); a 304 response means the cached copy can be used without downloading it again. Source: web.dev (Google), CC BY 4.0

The most common CDN-side pitfall is a situation where the origin blocks CDN IP addresses or drops connections, and the CDN (e.g. Cloudflare) maps this to 502. In that case, it is worth reviewing events in the dashboard (e.g. Firewall Events, Rate Limiting) and checking whether there are any firewall blocks on the origin (UFW/iptables, hosting provider rules) that are cutting off traffic from the CDN network. If the origin accepts traffic only from selected addresses, add the CDN’s official IP ranges to the allowlist and automate their updates, because otherwise 502 will return after changes on the provider’s side. In addition, bear in mind that inconsistency in the CDN cache after changes to paths on the origin can lead to requests hitting outdated resources, so sometimes you need a cache purge for specific URLs and alignment of cache-control rules.

A load balancer can cause 502 when there are no healthy targets or the health check is badly defined, even though the user can see that the site “sometimes works”. A common pitfall is a health check returning 301/302 or requiring authorisation, which is why it is standard practice to have a separate health endpoint (always 200 OK), independent of login and external dependencies. A separate category of issues concerns TLS between the LB and the backend. When the layers disagree about HTTP/HTTPS, communication errors appear, so it is worth checking, among other things, `X-Forwarded-Proto` and the HTTPS enforcement settings in the application. In addition, WAF can generate false positives (especially with uploads or JSON), so rather than disabling protection entirely, it is better to inspect the WAF logs for a specific request and test disabling a single rule or using “log only” mode.

Causes of the 502 error on the user side: how to identify and fix them?

On the user side, a 502 error most often stems from local issues with the network, DNS or intermediaries such as VPN/proxy services, which disrupt communication with the “gateway”. If the connection drops packets or breaks TCP/TLS, the intermediary layer may not receive a complete response and will return 502, even though the backend is working correctly. It also happens that the browser holds outdated cache of redirects or resources after configuration changes on the server side. If 502 occurs only on one device or in one network, that is a clear sign that it is worth starting with local diagnostics (network/DNS/cache/VPN), rather than with “fixes” on the server side.

  • Compare behaviour on another network (e.g. Wi‑Fi vs LTE) and on another device to confirm whether the problem is local in nature.
  • Check whether a VPN or corporate proxy is interfering with traffic (e.g. through its own TLS certificates). Turn them off briefly and run the test again.
  • Open incognito mode or perform a hard refresh (Ctrl+F5), then clear the cache for the domain if you suspect incorrect redirects or resources stored in the browser cache.
  • When you suspect DNS on the client side, clear the DNS cache (`ipconfig /flushdns` in Windows) or set DNS to 1.1.1.1 (Cloudflare) or 8.8.8.8 (Google), then restart the browser.
  • Temporarily disable extensions (e.g. ad blockers or security add-ons) and compare the result on a clean browser profile.
  • If the error concerns an API or integration, reproduce the request in `curl -v` or Postman and check whether the client is not sending unusual headers (e.g. `Host`, `Content-Length`) or is not dropping the connection.

In practice, 502s can also be triggered by “edge” client-side behaviour that increases load or the risk of communication failures. Excessive parallel requests (e.g. refresh loops or an aggressive script) can expose the backend’s limited capacity and make 502 appear only under greater pressure on the server. When dealing with TLS issues, it is also worth checking the system clock: if the clock is badly out of sync, certificates may appear invalid, which depending on the intermediary is sometimes ultimately reported as 502. If the error disappears after turning off VPN/proxy, correcting DNS and refreshing the cache, the cause is most often on your side (the intermediary, DNS or the browser), rather than the site itself.

FAQ

Frequently asked questions

How do you tell that it is a 502 error, not 500 or 504?

502 means that the intermediary server was unable to process the response from the backend correctly. Unlike 500, 503 and 504, it more often points to a faulty response or a broken connection between layers.

Why does a 502 error appear on the server side?

Most often, this happens when the upstream is down, is not listening on the port, or terminates the connection while responding. Other causes include resource exhaustion, OOM, proxy configuration errors or TLS issues.

When does a 502 error happen only for me, and when is it global?

If you see 502 only on your device, it is worth starting with simple client-side tests and checking different networks. When the problem is global, you need to focus on logs and service health.

What should you check in the headers when a 502 error appears?

It is worth reviewing the response headers, especially `server`, `via`, `cf-ray`, `x-cache` and similar fields. They can indicate whether the error is being generated by the CDN, load balancer or origin proxy.

What are the most common causes of a 502 error in Nginx, Cloudflare and Kubernetes?

In Nginx, a 502 usually means no response from PHP-FPM, Node, Gunicorn or another upstream. In Cloudflare and Kubernetes, it often involves an issue with the origin, healthy endpoints, routing or security rules.

What diagnostic steps should you take when dealing with a 502 error?

First check whether the problem affects the whole domain or just one path, then use `curl -v`, logs, `dig`, `traceroute` and direct tests to the upstream. Load metrics and comparing the error time with intermediary-layer logs are also helpful.

Contents