nginx 502 Bad Gateway with PHP-FPM: read the error log line first
A 502 means nginx got no usable answer from PHP-FPM. One line in the nginx error log says why: no socket, no permission, a dead worker or a big header.

On this page
Reload the page that fails and read the newest line in nginx's error log:
sudo nginx -T 2>/dev/null | grep -E '^\s*error_log'
sudo tail -n 5 /var/log/nginx/error.logThe first command prints where the log is, in case it's somewhere else: -T dumps the configuration after testing it. Then find your line here:
| Text in the line | Cause | Section |
|---|---|---|
connect() to unix:... failed (2: No such file or directory) | The socket doesn't exist | 1 |
connect() ... failed (111: Connection refused) | Nobody listens on it | 1 |
connect() to unix:... failed (13: Permission denied) | nginx may not open the socket | 2 |
connect() to unix:... failed (11: Resource temporarily unavailable) | The queue is full | 3 |
upstream prematurely closed connection | The worker died or was killed | 4 |
recv() failed (104: Connection reset by peer) | The same, a moment later | 4 |
upstream sent too big header | Response headers don't fit the buffer | 5 |
upstream timed out | This is a 504 | 6 |
Primary script unknown | This is a 404 | 7 |
The texts come from the nginx source and from PHP-FPM. nginx wasn't run for this page. PHP-FPM was: the FPM log lines below are from version 8.2.8, started with a small test pool and asked through its socket, with long paths shortened.
1. No socket, or nobody behind it
nginx and PHP-FPM have to agree on one address. On the nginx side it's fastcgi_pass, on the FPM side it's listen in the pool file. Print both:
sudo nginx -T 2>/dev/null | grep -n 'fastcgi_pass'
grep -rn '^listen *=' /etc/php/*/fpm/pool.d/
ls -l /run/php/An upgrade of PHP is the usual reason why they drift apart. The socket on Debian and Ubuntu carries the version, so after a step from 8.2 to 8.3 the server block still points at a name that no longer exists. Correct it in the server block, test and reload.
If the names agree, the service isn't running:
systemctl status 'php*-fpm' --no-pager
sudo php-fpm8.3 -t
sudo journalctl -u php8.3-fpm -n 30 --no-pager-t tests the configuration. A pool that lists a user that doesn't exist, or two pools with the same listen line, keep the whole service down.
2. Permission denied on the socket
The socket is a file with an owner. By default FPM creates it with mode 0660 and the user it runs as, according to the FPM manual, which also says that on Linux read and write permission is needed for a connection from a web server. So nginx needs to be the owner or in the group:
; pool file
listen = /run/php/shop.sock
listen.owner = www-data
listen.group = www-data
listen.mode = 0660Compare with the user line in nginx.conf. It's www-data in Ubuntu's package and often nginx in the one from nginx.org, and a mix of the two sources is how this error starts. Restart FPM after the change, because the socket is created at start. Don't set the mode to 0666: every local account could then send requests to PHP.
On systems with SELinux the permissions can be right and the answer is still 13. Look for a denial at the same second with sudo ausearch -m avc -ts recent before you change any mode.
3. All workers are busy
When every worker is occupied, new connections wait in the socket's queue. If the queue overflows, nginx gets error 11 at once. Before that point visitors only notice that the site is slow. PHP-FPM says so in its own log, once, when the limit is reached:
[25-Nov-2026 02:57:12] WARNING: [pool www] server reached pm.max_children setting (2), consider raising itThat pool had two workers, and three requests came in that each slept for three seconds. The message is a suggestion and not an order. Raising pm.max_children helps if the workers are waiting for something and the machine has memory to spare. If they're all busy computing, more of them only share the same processor. Find out what they do first. pm.status_path shows the state of the pool, and the slow log shows the place in the code:
pm.status_path = /fpm-status
request_slowlog_timeout = 3s
slowlog = /var/log/php-fpm/shop.slow.logFor a request that takes longer than the limit, FPM writes a line into its log and a stack trace into the slow log:
WARNING: [pool www] child 45869, script '/srv/shop/sleep.php' (request: "GET /sleep.php") executing too slow (1.302410 sec), loggingTracing needs the right to look into another process. If the main process lacks it, the log has a second line about missing privileges and the slow log stays empty. Keep the status address closed to the public, with the same kind of rule you'd put in front of phpMyAdmin.
4. The worker died in the middle
"Prematurely closed" means that the connection worked, PHP started, and then there was no one left. The FPM log has the reason under the same time. Three kinds exist.
A time limit. request_terminate_timeout ends a request from outside, whatever PHP is doing:
WARNING: [pool www] child 45869, script '/srv/shop/sleep.php' (request: "GET /sleep.php") execution timed out (2.303927 sec), terminating
WARNING: [pool www] child 45869 exited on signal 15 (SIGTERM) after 2.346839 seconds from startThe client in this run got an empty answer, which nginx reports as a 502. It explains a pattern that looks like a network fault: every request over 30 seconds fails, and it's exactly 30. PHP's own max_execution_time behaves better, because it ends the script with an error message and a 500 that your application can log. Set the FPM limit some seconds above it, as a safety net.
A crash. Signal 11 is a segmentation fault in PHP or in an extension:
WARNING: [pool www] child 45856 exited on signal 11 (SIGSEGV) after 1.664564 seconds from start
NOTICE: [pool www] child 45869 startedFPM replaces the worker by itself. Switch extensions off one at a time, starting with the ones that aren't part of PHP, and try opcache.enable=0 in the pool for a test. Very deep recursion can crash a worker as well.
The kernel. Signal 9 without any FPM timeout before it usually means that the machine ran out of memory:
journalctl -k --since "1 hour ago" | grep -i -E 'out of memory|killed process'Then there are too many workers for the memory, or one script takes too much. A script that reaches memory_limit isn't this case. It ends with "Allowed memory size exhausted", which is a normal PHP error and produces a 500 or a half page, and it's in the PHP log.
5. Too big a header
nginx reads the first part of the answer into one buffer, and the headers must fit. The module reference gives 4k or 8k as the default for fastcgi_buffer_size and calls the response invalid if the header is larger. Large cookies, long redirect addresses and frameworks that keep session data in cookies get there. How large are yours?
<?php
$headers = [
'Set-Cookie: session=' . str_repeat('a', 3800),
'Set-Cookie: cart=' . str_repeat('b', 2100),
'Location: https://example.com/login?next=' . rawurlencode(str_repeat('/shop', 40)),
];
$size = array_sum(array_map(fn ($h) => strlen($h) + 2, $headers));
echo $size, " bytes: ", $size > 4096 ? 'more than a 4k buffer' : 'fits', "\n";6264 bytes: more than a 4k bufferOn a real page use headers_list() in place of the sample array. The settings that go with each other:
fastcgi_buffer_size 16k;
fastcgi_buffers 16 16k;
fastcgi_busy_buffers_size 32k;Ask at the same time why a cookie has to be that large. The browser sends it back with every request, and the next limit it meets is the one for request headers.
6. When it's a 504
"Upstream timed out" turns into a 504 Gateway Timeout. nginx waited fastcgi_read_timeout, 60 seconds by default, between two reads, and gave up. PHP may still be working. Raising the number hides a slow page, so look at the slow log first. For an import or a report that has to take minutes, move the work into a command line job and let the page only start it.
Three limits should be in this order, from short to long: max_execution_time, then request_terminate_timeout, then fastcgi_read_timeout. With that order the most specific message always wins, and you read "Maximum execution time exceeded" with a file and a line in place of a bare 502 or 504.
7. "File not found." and Primary script unknown
This one is often searched together with 502, and it's a 404. PHP-FPM was reached, and it couldn't open the script whose path nginx sent. Here is the answer to a script that doesn't exist:
ERR: Primary script unknown
Status: 404 Not Found
File not found.The path is in the SCRIPT_FILENAME parameter. A wrong root, an alias combined with $document_root, a container that has the files in another folder, or a folder that the pool user may not enter lead here. Every folder on the way needs the execute bit for that user:
namei -l /srv/shop/public/index.phpAsk FPM without nginx
When both logs are silent, take nginx out of the picture. PHP can talk to the socket itself. Fifteen lines of PHP are enough for a yes or no:
<?php
function reachable(string $address): string
{
$s = @stream_socket_client($address, $errno, $error, 2);
return $s ? 'connected' : "$error ($errno)";
}
echo reachable('unix:///tmp/no-such-fpm.sock'), "\n";
echo reachable('tcp://127.0.0.1:1'), "\n";No such file or directory (2)
Connection refused (61)The numbers in brackets are the ones of the operating system. This run was on a Mac, where "refused" is 61; on Linux it's the 111 from the nginx log. Run the script as the nginx user, sudo -u www-data php test.php, and a permission problem shows up as number 13. If it connects and the page still fails, the problem is in what is sent and not in the connection, and sections 4, 5 and 7 remain.
A 502 only sometimes
Intermittent 502s have a short list of causes: workers that restart after pm.max_requests, a pool near its limit at busy hours, a deployment that reloads FPM, one page that crashes a worker, and several FPM machines behind one name of which one is broken. Put the times of the errors next to the FPM log. If each one matches a "child exited" line, it's section 4. If they come in clusters with a max_children warning at the start, it's section 3. Database trouble rarely shows as a 502, since PHP survives a lost MySQL connection and reports it as an error of its own.
Same subject
Where is php.ini? Finding the file PHP actually loads
Run php --ini for the command line, and call php_ini_loaded_file() through the browser for the website. They are often two different files, and both count.
Install phpMyAdmin on Ubuntu with nginx and PHP-FPM, the manual way
Download and verify the archive, unpack it outside the web root, write a server block with a PHP location, add config.inc.php and lock the address down.
PHP error reporting and the PHP error log: where the errors go
PHP decides three things about an error: whether to report it, whether to show it, and where to log it. Print those settings first, then read the file.
PHPSolvedThe fix first, then the reason