Nginx 502 Bad Gateway in front of a Docker container
502 Bad Gateway
nginx error log: connect() failed (111: Connection refused) while connecting to upstreamWhat's happening
A 502 from Nginx means it successfully received the request but couldn't get a response from the upstream app. 'Connection refused' specifically means nothing was listening on the host/port Nginx tried to reach. The most common cause when Nginx and the app are both in Docker: the `proxy_pass` target uses `localhost` or `127.0.0.1`, which inside Nginx's own container doesn't route to the app container at all. It also happens when the app hasn't started yet (Nginx started first) or the app is listening on `127.0.0.1` inside its own container instead of `0.0.0.0`, making it unreachable from outside that container even by service name.
Fix
1. Point `proxy_pass` at the Docker service name and internal port, not localhost:
```nginx
location / {
proxy_pass http://app:3000;
}
```
2. Make sure the app binds to `0.0.0.0`, not `127.0.0.1` — e.g. for Node: `app.listen(3000, '0.0.0.0')`.
3. Verify both containers share a network and the app's port is actually exposed in `docker-compose.yml` (`expose: ["3000"]`, not necessarily `ports:` if Nginx reaches it internally).
4. Check the app is actually up: `docker logs <app>` and `docker exec -it nginx curl -v http://app:3000`.
5. If it's intermittent only on deploy, add `proxy_next_upstream` and a startup delay/healthcheck so Nginx doesn't route to a container that's still booting.Got a different error? Paste it here for a free diagnosis.