
502 Bad Gateway: How to Fix It on Nginx
502 Bad Gateway on Nginx: read the error log, then fix PHP-FPM socket issues, stopped Node or Docker backends, crashed workers and small proxy buffers.
Ahmet Yılmaz
Senior Infrastructure Engineer
You deploy a change, restart a service, or upgrade PHP, and the site answers with a white page: "502 Bad Gateway" and, underneath, nginx/1.24.0 (Ubuntu). Nginx itself is clearly running, since it is the one showing the error. What it is telling you is that the application behind it did not give a usable answer.
That narrows things down a lot. This guide explains what 502 Bad Gateway means on Nginx, shows how to read the one log line that names the cause, and then fixes the common cases one by one: PHP-FPM that is stopped or listening on a different socket, socket permissions, Node or Python apps that are not listening where Nginx expects, workers that crash mid-request, oversized headers, and Docker containers that changed address.
What Does 502 Bad Gateway Mean?
A 502 status code means a server acting as a gateway or proxy received an invalid response from the upstream server it contacted (RFC 9110). In a typical setup, Nginx is that gateway:
- PHP sites: Nginx passes
.phprequests to PHP-FPM over a Unix socket or TCP port. - Node.js, Python, Go apps: Nginx reverse proxies to an app listening on a local port such as 3000 or 8000.
- Containers: Nginx forwards to another container by its service name.
If Nginx cannot connect, or the connection closes before a valid HTTP response arrives, the visitor gets a 502. The problem is almost always the backend, its address, or the permissions between the two; rarely the browser or the network. If you are setting up a proxy from scratch, our Nginx reverse proxy guide covers the full configuration.
Step 1: Read the Nginx Error Log
Nginx writes the precise reason for every 502 in its error log. Start there:
sudo tail -n 30 /var/log/nginx/error.log
# Follow it live and reload the failing page in the browser
sudo tail -f /var/log/nginx/error.log
Then check the backend directly, bypassing Nginx:
# Is PHP-FPM running, and which socket does it create?
systemctl status php8.3-fpm
ls -l /run/php/
# Is anything listening on the app port?
sudo ss -ltnp | grep -E ':3000|:8000'
# Ask the app directly
curl -i http://127.0.0.1:3000/
If curl to the backend works but the site still returns 502, the problem is in the Nginx configuration (wrong address, socket or buffers). If curl fails too, fix the backend first.
Error Log Message → Cause → Fix
These are the log lines behind nearly every 502 we see, and what each one means:
| Error log message | Likely cause | Fix |
|---|---|---|
connect() to unix:/run/php/php8.3-fpm.sock failed (2: No such file or directory) | PHP-FPM stopped, or a different PHP version's socket | Start PHP-FPM; match fastcgi_pass to the real socket |
connect() to unix:/run/php/...sock failed (13: Permission denied) | Nginx user cannot open the socket | Fix listen.owner, listen.group, listen.mode |
connect() failed (111: Connection refused) while connecting to upstream | Nothing listening on that host and port | Start the app; check host, port and IPv4/IPv6 |
upstream prematurely closed connection while reading response header | Backend process crashed or was killed mid-request | Check PHP-FPM / app logs, memory and OOM killer |
upstream sent too big header while reading response header | Cookies or headers larger than proxy buffers | Increase fastcgi_buffer* or proxy_buffer* |
no live upstreams while connecting to upstream | All servers in an upstream block marked failed | Fix backends; review max_fails and health |
host not found in upstream "app" | Name cannot be resolved (often Docker) | Check service name, network and resolver |
Tip: grep -c "upstream" /var/log/nginx/error.log gives you a quick count, and grep upstream /var/log/nginx/error.log | tail -5 shows the most recent cases with timestamps you can match to deploys or restarts.
How to Fix 502 Bad Gateway on Nginx
Work through the fix that matches your log message. After each change, reload the affected service and test the page again before moving on to the next one.
Fix 1: PHP-FPM Is Down or the Socket Path Is Wrong
The most common 502 on PHP sites. The socket name contains the PHP version, so after upgrading from 8.2 to 8.3 or 8.4, the old path in the Nginx config points at nothing.
sudo systemctl start php8.3-fpm
sudo systemctl enable php8.3-fpm
ls /run/php/ # e.g. php8.3-fpm.sock
Make the Nginx config match the socket that actually exists:
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php8.3-fpm.sock;
}
sudo nginx -t && sudo systemctl reload nginx
If PHP-FPM refuses to start, sudo php-fpm8.3 -t tests its configuration and prints the line it does not like.
Fix 2: Permission Denied on the Socket
Nginx runs as www-data on Ubuntu and Debian. If the PHP-FPM pool creates its socket with another owner or a strict mode, Nginx cannot connect. Check the pool file:
; /etc/php/8.3/fpm/pool.d/www.conf
listen = /run/php/php8.3-fpm.sock
listen.owner = www-data
listen.group = www-data
listen.mode = 0660
sudo systemctl restart php8.3-fpm
ls -l /run/php/php8.3-fpm.sock # srw-rw---- www-data www-data
On RHEL-family systems such as Rocky Linux or AlmaLinux, SELinux can block Nginx from connecting to a TCP upstream with the same 13: Permission denied message. Allow it with sudo setsebool -P httpd_can_network_connect 1 rather than disabling SELinux.
Fix 3: Connection Refused From a Node.js or Python App
111: Connection refused means nothing is listening where Nginx is knocking. Common reasons:
- The app crashed or was never started after a reboot.
- It listens on a different port than
proxy_passuses. - IPv4 vs IPv6:
proxy_pass http://localhost:3000can resolve to::1first, while the app only listens on127.0.0.1, or the other way round. Logs then showconnect() to [::1]:3000 failed.
Use an explicit address on both sides:
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
And keep the app running under a supervisor, so it restarts after crashes and reboots. With PM2 that is pm2 start app.js --name app, pm2 save and pm2 startup; our guide to Node.js in production with PM2 and Nginx walks through it on Node 22 and 24 LTS.
Fix 4: Workers Crash or Run Out
upstream prematurely closed connection means the backend accepted the request and then died. Look at why:
# Killed by the kernel for using too much memory?
sudo journalctl -k --since "1 hour ago" | grep -i -E "oom|killed process"
# PHP-FPM complaints: crashes and exhausted pools
sudo journalctl -u php8.3-fpm --since "1 hour ago" | grep -i -E "exited on signal|max_children"
If you see server reached pm.max_children setting, PHP-FPM has no free workers and requests queue up, which shows up as 502 or 504 errors under load. Size the pool from real memory use rather than guessing:
# Average memory per PHP-FPM worker, in MB
ps --no-headers -o rss -C php-fpm8.3 | awk '{s+=$1} END {printf "%.0f MB\n", s/NR/1024}'
; Example: about 2 GB for PHP, workers average 80 MB → 2048 / 80 ≈ 25
pm = dynamic
pm.max_children = 25
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 10
pm.max_requests = 500
pm.max_requests recycles workers periodically, which contains slow memory leaks. If the server simply does not have the memory for the traffic, more workers will only trigger the OOM killer; that is the point to add RAM or move to larger cloud hosting. Our PHP 8 performance guide covers OPcache and other ways to cut per-request cost first.
Warning: Do not raise pm.max_children without checking memory. A pool that is larger than RAM allows turns occasional 502s into a server that swaps heavily or has its processes killed.
Fix 5: Upstream Sent Too Big Header
Large cookies, long redirect headers or many Set-Cookie lines can exceed Nginx's default buffers. Increase them in the server or location block that handles the request:
# PHP-FPM
fastcgi_buffer_size 32k;
fastcgi_buffers 16 16k;
# Reverse proxy to an app
proxy_buffer_size 16k;
proxy_buffers 8 16k;
proxy_busy_buffers_size 32k;
Then reload Nginx. If headers keep growing, find out why; a session cookie that grows on every request is a bug worth fixing.
Fix 6: Docker and Changing Container Addresses
When Nginx runs in a container and proxies to http://app:3000, it resolves app once at startup. If the app container is recreated and gets a new IP, Nginx keeps using the old one and returns 502 until it is reloaded. Two checks and a fix:
docker compose ps # is the app container up and healthy?
docker compose logs --tail=50 app # did it crash on start?
# Re-resolve names through Docker's internal DNS
resolver 127.0.0.11 valid=10s;
location / {
set $app_upstream http://app:3000;
proxy_pass $app_upstream;
}
Also make sure both containers are on the same Compose network and that the app listens on 0.0.0.0 inside its container, not 127.0.0.1. The Docker Compose multi-service guide shows a complete example.
How to Prevent 502 Errors
- Restart services automatically. Use
Restart=on-failurein systemd units; PM2 does the same for Node. - Reload instead of restart during deploys.
systemctl reload php8.3-fpmreplaces workers without dropping requests in flight;restartopens a short 502 window. - Turn PHP upgrades into a checklist. Install the new version, update the socket path in Nginx, run
nginx -t, and only then stop the old version. - Monitor from outside. An external check tells you about a 502 before customers do; see our guide to uptime monitoring with Alertmanager.
502 Bad Gateway Behind Cloudflare or a Load Balancer
If a CDN or load balancer sits in front of Nginx, first find out which layer produced the 502. A branded Cloudflare 502 page or a cloud load balancer's error means that layer could not get a good answer from your server: check that Nginx is reachable on the right port, that the firewall allows the proxy's IP ranges, and that TLS settings match. A plain Nginx 502 means the problem is behind Nginx, and everything above applies.
# Test the origin directly, skipping the CDN
curl -sI https://www.example.com --resolve www.example.com:443:203.0.113.10
Frequently Asked Questions
What does 502 bad gateway mean?
It means a proxy server, usually Nginx, could not get a valid response from the application behind it. The web server is running, but PHP-FPM, Node or another backend is stopped, unreachable or crashed while answering.
Is a 502 bad gateway error my fault?
As a visitor, no. The problem is between the site's proxy and its backend. Reloading after a minute can help if the backend was restarting, but the site owner has to fix the cause.
How do I fix 502 bad gateway on Nginx with PHP-FPM?
Read /var/log/nginx/error.log first. Start PHP-FPM if it is stopped, make sure fastcgi_pass points to the existing socket such as /run/php/php8.3-fpm.sock, and check that the socket's owner and group match the Nginx user.
What does nginx/1.24.0 (Ubuntu) mean on a 502 page?
It is simply the Nginx version string; 1.24.0 is the version packaged with Ubuntu 24.04. It tells you Nginx generated the error, not that Nginx is broken. You can hide it with server_tokens off.
What is the difference between 502 and 504?
A 502 means the backend returned an invalid response or refused the connection. A 504 means the backend accepted the request but did not answer within Nginx's timeout, which usually points to slow code or database queries.
Why does 502 bad gateway appear only under heavy traffic?
Usually the backend runs out of workers or memory. PHP-FPM reaching pm.max_children, or the kernel killing processes for using too much memory, both show up as 502s at peak times. Check the FPM and kernel logs.
Conclusion
A 502 Bad Gateway on Nginx means the proxy works and the backend does not answer properly. The Nginx error log names the reason in one line: a missing or wrong PHP-FPM socket, permission denied, connection refused, a worker that crashed, a header too big for the buffers, or a name that no longer resolves. Test the backend directly with curl, fix the specific cause, validate with nginx -t, and keep backends under a supervisor with enough memory so the next restart does not take the site down. For deeper Nginx tuning, see our Nginx configuration guide.
Run your apps on infrastructure that keeps up
Hosted Cloud cloud hosting starts at $6.60 per month with a 99.95% uptime SLA, free site migration and 24/7 support with a 15-minute first response.
Ahmet Yılmaz
Senior Infrastructure Engineer
With over 10 years of experience in cloud infrastructure and DevOps, Ahmet specializes in Kubernetes, Terraform, and high-availability architectures.
Comments coming soon