Knowledge
502 Bad Gateway in nginx
#Errors
A 502 Bad Gateway means nginx reached your application but got an invalid response back. In almost every case the backend (PHP-FPM) crashed, never started, or is unreachable.
Published by Mark van Eijk on June 23, 2026 · 1 minute read
About error 502
A 502 Bad Gateway is returned by nginx when it is acting as a reverse proxy and receives an invalid response from the upstream server it forwards requests to. For a PHP application that upstream is almost always PHP-FPM.
The important thing to understand: nginx itself is fine. The problem sits behind nginx, in the service it is trying to talk to.
Why do I see this error
The most common causes, roughly in order:
- PHP-FPM is not running, crashed, or was never started.
- nginx points to the wrong PHP-FPM socket or port (a typo in
fastcgi_pass). - The socket file exists but the nginx user can't read it (wrong permissions).
- The backend died halfway through the request (often an out of memory kill).
Always start by reading the nginx error log, it names the exact reason:
tail -f /var/log/nginx/error.log
You'll see a line ending in something like connect() to unix:/run/php/php8.3-fpm.sock failed (2: No such file or directory) or (111: Connection refused). That bracketed code tells you everything.
Solution
First, check whether PHP-FPM is actually running and start it if not:
systemctl status php8.3-fpm
systemctl restart php8.3-fpm
Then confirm nginx is pointing at the socket that PHP-FPM actually listens on. The path in your nginx config must match the listen directive in the pool config (/etc/php/8.3/fpm/pool.d/www.conf):
location ~ \.php$ {
fastcgi_pass unix:/run/php/php8.3-fpm.sock;
include fastcgi_params;
}
If the socket exists but you still get (13: Permission denied), make sure the pool runs as the same user as nginx (usually www-data):
user = www-data
group = www-data
listen.owner = www-data
listen.group = www-data
Reload both services after any change:
systemctl reload php8.3-fpm
systemctl reload nginx
If the backend keeps dying mid-request rather than refusing the connection, the cause is usually resources, not configuration. Check the 504 Gateway Timeout article for slow responses, and PHP allowed memory size exhausted for out of memory kills. When the backend is up but every worker is busy, you'll see a 503 Service Unavailable instead.
Subscribe to our newsletter
Do you want to receive regular updates with fresh and exclusive content to learn more about web development, hosting, security and performance? Subscribe now!
Related articles
Error in the HTTP2 framing layer
A 502 Bad Gateway means nginx reached your application but got an invalid response back. In almost every case the backend (PHP-FPM) crashed, never started, or is unreachable.
413 Request Entity Too Large in nginx
A 502 Bad Gateway means nginx reached your application but got an invalid response back. In almost every case the backend (PHP-FPM) crashed, never started, or is unreachable.