502 Bad Gateway after deploying: what it means and how to fix it
The proxy in front of your app reached for it and got no valid answer: nothing was listening on the port it tried, or the process closed the connection mid-request. After a deploy that is almost always one of five things: the app listens on the wrong port or on 127.0.0.1, it crashed on start, it was still starting, it ran out of memory, or the proxy points at the wrong port. The app's own log says which.
By Livops team, the people who build and run LivopsUpdated
What the browser shows, when nginx is the proxy[4]:
502 Bad Gateway
nginx
Other proxies and platforms word it as “Bad Gateway”, “upstream connect error” or “application failed to respond”, but the meaning is the same. This page explains what the proxy is telling you, lists the causes that show up after a deploy from the most common, says how to read each one in the app’s log, and gives the fix per stack. The most common cause, an app listening on the wrong port or address, has its own page: App not listening on $PORT.
What does 502 Bad Gateway mean?
A 502 says that a server acting as a gateway or proxy got an invalid response from the server behind it[1]. In a deployed app, the gateway is the platform’s proxy (nginx, a load balancer, an edge server) and the server behind it is your app. The proxy is fine; the hop to your app failed.
nginx makes the split visible. It answers 504 Gateway Time-out when it gave up waiting, and 502 for the other upstream failures: a refused connection, a connection closed early, an invalid answer[2]. RFC 9110 defines 504 the same way: no timely response from the upstream[1]. So a 502 is rarely “too slow”; it is “nothing there” or “it hung up”.
If you run nginx yourself, its error log names the failure. These lines are built from nginx’s own messages[2]:
connect() failed (111: Connection refused) while connecting to upstream, client: …, upstream: "http://127.0.0.1:3000/"
upstream prematurely closed connection while reading response header from upstream, client: …
Connection refused means nothing was listening on that address and port. Prematurely closed means the app accepted the connection and then went away before it answered — usually a crash or a killed process.
Causes, most common first
1. The app is not listening where the proxy connects
The app listens on its own port (app.listen(3000), Uvicorn’s default 8000[5]) while the platform sends traffic to the port in PORT, or it listens on 127.0.0.1, which only accepts connections from inside its own container. Uvicorn binds 127.0.0.1 unless you pass --host[5]; Gunicorn binds 127.0.0.1:8000 when PORT is not set[6].
The log usually looks healthy — “Listening on http://localhost:8000” — and that is the clue: the address in that line is not the one the proxy uses. The fix and a way to test it are on App not listening on $PORT.
2. The app crashed on start
A missing variable, a missing module, a database it could not reach. The process exits, nothing listens, and every request gets a refused connection. The proxy page says nothing about why; the last lines of the app’s log do:
KeyError: 'DATABASE_URL'
ModuleNotFoundError: No module named 'psycopg'
Error: connect ECONNREFUSED 127.0.0.1:5432
Fix the error in the log and the 502 goes with it. The common ones have their own pages: ModuleNotFoundError, ECONNREFUSED to the database, Gunicorn: Worker failed to boot.
3. The app was still starting
Migrations, a model download, a cache warm-up or a slow import run before the server starts listening. Until then the port is closed, and requests that arrive in that window get 502. If the proxy keeps the old version only until the new one’s process exists, rather than until it answers, every deploy has this window.
Start listening first and do slow work afterwards, or move migrations into a step that runs before the start. If you run nginx yourself, proxy_connect_timeout and proxy_read_timeout both default to 60 seconds[3], but they do not help here: a closed port is refused at once, not waited for.
4. The process ran out of memory
The kernel kills a process that goes over its memory limit, and every connection it held is cut — a 502 for each request in flight, and for every request after it until something restarts it. The log ends with Killed, or the process exits with code 137. Gunicorn says so in its own words when a worker is killed this way[7]:
Worker (pid:42) was sent SIGKILL! Perhaps out of memory?
Look at what grows: a large file read into memory, an image processed at full size, a cache with no limit, too many workers for the memory you have. Each Gunicorn worker is a separate process with its own copy of the app.
5. A request takes longer than a worker is allowed
Gunicorn kills a worker that is silent for more than its timeout, 30 seconds by default[6], and logs it[7]:
[CRITICAL] WORKER TIMEOUT (pid:42)
The request that worker was serving loses its connection, which the proxy reports as 502, even though the cause is a slow request. Make the slow work asynchronous (a queue and a worker process), or raise --timeout for that app. When the proxy’s own timeout runs out first, you get 504 instead[2][3].
6. The proxy points at the wrong port
On your own server: proxy_pass http://127.0.0.1:8000; in nginx while the app listens on 3000. On a platform: the port set for a Docker image does not match what the image listens on. The app is healthy and reachable on its own port; the proxy is knocking on another one. Make the two numbers the same.
The fix, per stack
Node (Express, Fastify, plain http)
const port = Number(process.env.PORT) || 3000
app.listen(port, '0.0.0.0', () => console.log('listening on 0.0.0.0:' + port))
Next.js
next start reads PORT and listens on 0.0.0.0 by default[8], so the start script needs no flags:
"scripts": { "start": "next start" }
If you added -p 3000 or -H localhost to it, remove them.
FastAPI and other ASGI apps (Uvicorn)
.venv/bin/uvicorn main:app --host 0.0.0.0 --port $PORT
Django and Flask (Gunicorn)
With PORT set, Gunicorn binds 0.0.0.0:$PORT by itself[6]. Keep the worker count small enough for the memory you have:
.venv/bin/gunicorn myproject.wsgi --workers 2 --timeout 60
.venv/bin/gunicorn app:app --workers 2
A Docker image
The image must listen on the port the platform is told about. Check the image’s EXPOSE line and its start command, not just the Dockerfile you remember writing.
How to confirm the fix locally
Run the app the way a platform does — a PORT you choose, reached from outside the process:
PORT=4321 npm start &
curl -i http://127.0.0.1:4321/
lsof -nP -iTCP:4321 -sTCP:LISTEN
The listening address should be *:4321 or 0.0.0.0:4321, not 127.0.0.1:4321. The closest match to a platform is a container, where localhost inside is not reachable from outside:
docker run --rm -e PORT=8080 -p 8080:8080 myapp
curl -i http://localhost:8080/
If curl gets an answer, a proxy will too. For a memory problem, docker run --memory 512m … reproduces the limit, and docker stats shows how close the app gets to it.
On Livops
- A web app listens on PORT. A
webservice must listen on the port in thePORTvariable, 3000 by default; for a Docker image, the port you specified, which must be 1024 or higher. The container runs as user 1000 with no Linux capabilities, so an image that listens on port 80 does not work. A Telegram bot or a background worker opens no port at all: make it a Bot or aworker, not a web app. - What a visitor sees. When a running app does not accept the connection, the Livops proxy answers 502 with the plain text
application is not responding. That text means the request reached Livops and the app behind it did not answer, not that the domain or HTTPS is wrong. - A new version has to answer before it serves. Livops waits up to a minute for a new version to answer. If it does not, the deploy fails as
start_failed, nothing is switched, and a web app’s previous version keeps running, so a version that never answers does not take the live address down. To check a specific route, sethealthPathinlivops.json, for example"/healthz". - The log says why. The Logs page shows the app’s last lines, often with a Tip: line under them that says what to do. The same log is on the terminal with
livops logs <service> -f, and over MCPget_logsreturns up to 5000 lines. - Out of memory is named. An app that used more memory than its plan allows is stopped, and the log says
Killedor exit code 137. Choose a bigger memory tier in the project’s settings —256,512,1024or2048MiB — or use less.get_metricsover MCP shows the service’s CPU and memory for the last hour, day or week. - 5xx answers are counted. The project’s Traffic tab counts responses from the access log of the edge server in front of the app: Server errors is every 5xx, and Responses by status shows when they started, per hour or per day.
- One click back. Recent versions are kept; roll back to a previous one from the Deploys list while you fix the new one. The assistant button next to a failed deploy reads the log and says what to change.
An app or a server costs 39 credits a month (39,000 so’m); see Pricing. The start errors are in The app did not start, including Out of memory and The app listens on localhost, and PORT, healthPath and memory are in Frameworks and livops.json.
Questions
Is a 502 a problem with my code or with the server?
Nearly always with the app behind the proxy. The proxy worked: it accepted the request and tried to pass it on. What failed was the next hop, your app, which was not listening, had crashed, or closed the connection. The app's own log, not the proxy's page, says why.
What is the difference between 502 and 504?
A 502 means the proxy got an invalid answer or none at all: the connection was refused or closed. A 504 means it waited and nothing came back in time. nginx answers 504 when its timeout runs out and 502 for the other upstream failures.
Why do I get 502 only right after a deploy, and then it works?
The proxy switched traffic to the new version before it was listening, or stopped the old one first. Requests in that window find nothing on the port. A platform that waits until the new version answers before switching does not have this window.
Why does my app work locally but return 502 after deploy?
Locally you open whatever port the app chose, from the same machine, so 127.0.0.1 works. After a deploy the proxy connects from outside the app's container, to the port the platform gave it. An app that listens on its own port or on 127.0.0.1 is unreachable there.
Can running out of memory cause a 502?
Yes. When the kernel kills a process that went over its memory limit, every request it was serving loses its connection, and the proxy reports 502 for them. The log shows Killed or exit code 137, and Gunicorn logs that a worker was sent SIGKILL and asks whether it ran out of memory.
Does Livops show a 502 when a new version fails to start?
A web app's new version has to answer on its port within a minute. If it does not, the deploy fails as start_failed and the previous version keeps serving, so the live address keeps working while you read the log.
Sources
- RFC 9110 — HTTP Semantics, 502 Bad Gateway and 504 Gateway Timeout (rfc-editor.org). Checked .
- nginx source — src/http/ngx_http_upstream.c (raw.githubusercontent.com). Checked .
- nginx docs — Module ngx_http_proxy_module (nginx.org). Checked .
- nginx source — src/http/ngx_http_special_response.c (raw.githubusercontent.com). Checked .
- Uvicorn — Settings (uvicorn.dev). Checked .
- Gunicorn — Settings (gunicorn.org). Checked .
- Gunicorn source — gunicorn/arbiter.py (raw.githubusercontent.com). Checked .
- Next.js docs — next CLI (nextjs.org). Checked .
Put your project online today
Connect GitHub or drop a folder. No card is asked for.
Deploy your appRelated
- App not listening on $PORT: why the health check failed after deployThe platform started your app, tried the port it gave it, and nothing answered in time. Almost always the app listens on its own fixed port instead of the PORT variable, listens on localhost (127.0.0.1) instead of 0.0.0.0, or crashed or was still starting when the check gave up. Listen on 0.0.0.0 and the port in PORT, and it passes.
- Gunicorn "Worker failed to boot": what it means and how to fix itGunicorn's worker could not load your application, so the master process shut down. The cause is the Python traceback printed just above the message: most often a missing package or variable, or a wrong module:variable path in the gunicorn command. Fix what the traceback names and the workers boot.
- Error: listen EADDRINUSE: address already in use — how to fix itYour server tried to listen on a port that another process on the same machine already holds. On your computer, stop the old process, usually a dev server still running in another terminal. In a deploy, it almost always means the app starts its server twice, or two processes in one container ask for the same port.
- ECONNREFUSED / Connection refused: why the app cannot reach its database after deployNothing was listening at the address your app tried. When the address is 127.0.0.1 or localhost, the app never read the database's real address: DATABASE_URL is not set, is not read, or is read during a build that has no database. Attach the database, read DATABASE_URL (or REDIS_URL, MYSQL_URL) at runtime, run migrations before the start rather than in the build, and keep the connection pool under the server's limit.
- ModuleNotFoundError: No module named — after a deployPython searched sys.path and could not find the module you import. After a deploy that almost always means the package is not in requirements.txt, is listed under a different name than the one you import, or the start command runs a Python that the packages were not installed into.
- JavaScript heap out of memory during next build: how to fix itNode's JavaScript heap reached its limit while Next.js was building, and V8 stopped the process. Raise the heap limit with NODE_OPTIONS=--max-old-space-size, staying below the memory the build really has, and cut what the build holds in memory: source maps, type checking during the build, and heavy dependencies.