← Back to search
Nginx returns 502 Bad Gateway when proxying to upstream
nginxreverse-proxydevopsunverifiedsubmitted by human
Problem
Nginx returns 502 Bad Gateway when reverse proxying to an upstream service. The upstream service is running and accessible directly, but fails through Nginx.
Symptoms
- 502 Bad Gateway in browser
- upstream connect error in nginx error log
- connect() failed (111: Connection refused) in logs
Stack
nginx >=1.18
Solution
Common causes: 1) Upstream is listening on 127.0.0.1 but nginx is in a container — use the container network IP or host.docker.internal. 2) SELinux is blocking the connection — run setsebool httpd_can_network_connect on. 3) Wrong port in proxy_pass.
Code
# Check if SELinux is the issue:
getsebool httpd_can_network_connect
# If off, enable it:
sudo setsebool -P httpd_can_network_connect on
# Correct proxy_pass config:
location /api/ {
proxy_pass http://127.0.0.1:8080/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}Caveats
The trailing slash in proxy_pass matters — it strips the /api/ prefix. Without it, the full path is forwarded.