The server you reached is acting as a gateway or proxy and received an invalid response from the upstream server it was trying to reach. The server handling your request is working fine, but the backend server behind it is not responding correctly.
HTTP 502 Bad Gateway is a server error status code indicating that a server acting as a gateway or proxy received an invalid response from an upstream server. In modern web architecture, requests often pass through multiple layers: a CDN, a load balancer, a reverse proxy (like Nginx), and finally the application server. When one of these intermediate layers cannot get a valid response from the next layer in the chain, it returns 502 to the client.
The most common cause of 502 errors is the backend application server being down or unresponsive. When Nginx or a cloud load balancer tries to forward a request to the application and the application process has crashed, is out of memory, or is not listening on the expected port, the proxy has no valid response to return to the client. The result is a 502 Bad Gateway error. This is why 502 errors are often transient, resolving when the application process restarts.
Distinguishing between 502 Bad Gateway, 503 Service Unavailable, and 504 Gateway Timeout is important for troubleshooting. A 502 means the proxy got an invalid response or no connection at all. A 503 means the server is temporarily overloaded and cannot handle requests. A 504 means the proxy connected to the upstream but it did not respond within the timeout window. Each code points to a different layer of the infrastructure, helping operations teams quickly identify and resolve the issue.
The backend application server behind the reverse proxy (Nginx, Apache, or cloud load balancer) has crashed, is not running, or is unreachable on the network.
The backend application took too long to respond and the proxy timed out waiting. This is different from 504 Gateway Timeout, which occurs when the proxy explicitly times out. A 502 means the proxy received a bad or no response.
The backend server returned a malformed response that the proxy cannot interpret. This can happen when the application crashes mid-response or returns data the proxy does not understand.
The proxy cannot resolve the hostname of the upstream server. This occurs when DNS records are missing, expired, or the DNS server itself is unreachable.
Verify that the upstream application server is running and accepting connections. Check process managers like PM2, systemd, or Docker to ensure the application process is alive.
Check your Nginx, Apache, or load balancer configuration to ensure the upstream server address and port are correct. Verify timeouts, buffer sizes, and connection pool settings.
Check the backend application logs for crashes, out-of-memory errors, or unhandled exceptions that caused the process to terminate while handling the request.
If the backend is slow but eventually responds, increase the proxy_read_timeout and proxy_connect_timeout values in your reverse proxy configuration to give the backend more time.
// Express.js — proxy error handling and health checks
const express = require('express');
const axios = require('axios');
const app = express();
const UPSTREAM_URL = process.env.UPSTREAM_URL || 'http://localhost:4000';
// Proxy requests to upstream with error handling
app.all('/api/*', async (req, res) => {
try {
const response = await axios({
method: req.method,
url: `${UPSTREAM_URL}${req.path}`,
data: req.body,
headers: { 'Content-Type': req.headers['content-type'] },
timeout: 30000 // 30 second timeout
});
res.status(response.status).json(response.data);
} catch (err) {
if (err.code === 'ECONNREFUSED' || err.code === 'ENOTFOUND') {
return res.status(502).json({
error: 'Bad Gateway',
message: 'Upstream server is not reachable'
});
}
if (err.response) {
return res.status(err.response.status).json(err.response.data);
}
res.status(502).json({
error: 'Bad Gateway',
message: 'Invalid response from upstream server'
});
}
});
// Health check endpoint for load balancers
app.get('/health', (req, res) => {
res.json({ status: 'healthy', timestamp: new Date().toISOString() });
});
# Flask — proxy error handling and health checks
from flask import Flask, jsonify, request
import requests as http_client
import os
app = Flask(__name__)
UPSTREAM_URL = os.environ.get('UPSTREAM_URL', 'http://localhost:4000')
@app.route('/api/<path:path>', methods=['GET','POST','PUT','DELETE'])
def proxy(path):
try:
resp = http_client.request(
method=request.method,
url=f'{UPSTREAM_URL}/api/{path}',
json=request.get_json(silent=True),
headers={'Content-Type': request.content_type or 'application/json'},
timeout=30
)
return jsonify(resp.json()), resp.status_code
except http_client.ConnectionError:
return jsonify(
error='Bad Gateway',
message='Upstream server is not reachable'
), 502
except http_client.Timeout:
return jsonify(
error='Gateway Timeout',
message='Upstream server did not respond in time'
), 504
except ValueError:
return jsonify(
error='Bad Gateway',
message='Invalid response from upstream server'
), 502
@app.route('/health', methods=['GET'])
def health_check():
return jsonify(status='healthy')
HTTP 502 means the proxy received an invalid response from the upstream server, or could not connect at all. HTTP 504 means the proxy connected to the upstream but it did not respond before the timeout expired. 502 is a connection or response problem, while 504 is a timeout problem.
Yes, if your application code crashes during request handling, the proxy sees an incomplete or invalid response and returns 502. Common code-level causes include unhandled exceptions, out-of-memory errors, and infinite loops that exhaust resources.
Yes. 502 errors are often transient, especially when caused by application restarts or temporary network issues. Implement retry logic with exponential backoff. If the error persists, it indicates a more serious infrastructure problem.
Cloud platforms use reverse proxies in front of your application. If your serverless function or container crashes, exceeds memory limits, or takes too long to respond, the platform's proxy returns 502 because it could not get a valid response from your code.
Implement proper error handling in your application, use process managers that auto-restart crashed processes, set up health checks for load balancers, monitor resource usage, and configure appropriate timeout values in your proxy.
Get instant alerts when your endpoints go down. 60-second checks, free forever.
Start Monitoring Free →