iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more
Need a server to try this on? Antihost offers Linux VPS plans with NVMe storage, full root access and a 14-day free trial.
A 502 from Nginx usually means it could not establish or complete a request to PHP-FPM. Start by reproducing one failed request while watching Nginx’s configured error_log; the exact errno tells you whether the socket is missing, refusing connections, blocked by permissions, timing out, or being closed by PHP-FPM. Then verify that the active PHP-FPM pool’s listen endpoint exactly matches Nginx’s fastcgi_pass, repair Unix-socket access if necessary, and check FPM capacity before changing timeouts.
Start with the Nginx error log
Do not begin by changing configuration at random. Nginx records upstream connection failures in the server’s configured error_log. Find the effective log path in the relevant Nginx configuration, then reproduce one failing PHP request while following the log:
Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteWindows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallsudo tail -n 100 /var/log/nginx/error.log
# In another terminal, request the failing URL
curl -i https://example.com/problem.php
Your distribution may use a different path, or a server or location block may override the global setting. Use the complete log line, including the upstream endpoint and errno, as the starting point for diagnosis. Nginx writes a message at the closest applicable error_log level, so a location-specific setting can explain why the line is not where you expected.
Decode the common messages
| Log pattern | What it indicates | Checks to perform |
|---|---|---|
connect() ... failed (2: No such file or directory) |
The Unix-socket path named by Nginx does not exist when the request arrives. | Confirm PHP-FPM is running, identify the active pool, and compare its listen path with fastcgi_pass. Check that the parent directory exists. |
connect() failed (111: Connection refused) |
The selected TCP port or Unix socket is present but not accepting connections. | Inspect the FPM service and journal, then verify that both sides use the same endpoint and that FPM successfully started. |
connect() ... failed (13: Permission denied) |
The socket exists, but the Nginx worker cannot open it. | Inspect socket owner, group, mode, every parent-directory traversal permission, and the pool’s listen.owner, listen.group, and listen.mode. |
upstream timed out |
Nginx did not receive the next upstream response data within the configured interval. | Investigate slow PHP work, an exhausted FPM pool, database or external-service waits, and queue depth before increasing fastcgi_read_timeout. |
upstream prematurely closed or recv() failed |
PHP-FPM or the application closed or reset the connection before Nginx completed the response. | Read the PHP-FPM pool log and system journal for worker exits, fatal errors, startup failures, or resource limits; correlate the timestamp with the request. |
The errno interpretation is operational guidance; the full error-log entry remains authoritative. A single 502 can have a different cause from the next one, so capture a fresh line while reproducing the problem.
#1 Best Overall
- Includes Raspberry Pi 5 with 2.4Ghz 64-bit quad-core CPU (8GB RAM)
- Includes 128GB Micro SD Card pre-loaded with 64-bit Raspberry Pi OS, USB MicroSD Card Reader
- CanaKit Turbine Black Case for the Raspberry Pi 5
- CanaKit Low Noise Bearing System Fan
- Mega Heat Sink - Black Anodized
Why nginx -t can pass while PHP still returns 502
Run this after editing Nginx files:
sudo nginx -t
The test checks whether Nginx can parse its configuration and start with it. It does not connect to PHP-FPM, verify that a Unix socket exists, test socket permissions, or prove that a TCP listener is accepting requests. Nginx can therefore report a successful syntax test while every PHP request fails. As an Nginx developer has explained, upstream reachability matters when a request is processed, not when Nginx parses its configuration.
Use nginx -t as a syntax gate, not as an upstream health check. After a successful test, reload Nginx so workers receive the corrected configuration:
Do these 3 things before closing this tab:
1Clear out junk files and repair common Windows errors2Scan for outdated or missing drivers - takes under a minute3Repair Windows errors before they cause bigger problemssudo systemctl reload nginx
Then test PHP-FPM separately and reproduce the request again. If the test succeeds but the old error remains, make sure the request is reaching the server block you edited and that the worker reload completed.
Verify the PHP-FPM service and the active pool
Service names include the installed PHP version and vary by distribution. The following example uses PHP 8.3; substitute the unit that actually exists on your host:
sudo systemctl status php8.3-fpm
sudo systemctl --failed
sudo journalctl -u php8.3-fpm --since "15 minutes ago"
If the guessed unit is absent, list installed units or inspect your package manager rather than repeatedly restarting a name copied from another server. A failed start, a missing runtime directory, an invalid pool directive, or a resource-limit error will appear in the service status or journal.
Locate the pool configuration, commonly under /etc/php/<version>/fpm/pool.d/, and identify the pool handling the request. Read its effective listen = ... setting. Every PHP-FPM pool must define an address on which it accepts FastCGI connections. If several pools exist, confirm which one serves the site; fixing an unused pool has no effect.
The Tool Desk
Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Now inspect the Nginx server block and the PHP location, often in a file under /etc/nginx/sites-enabled/ or /etc/nginx/conf.d/. Read the fastcgi_pass directive. These two values must describe the same Unix socket or the same TCP endpoint.
Rank #2
- 【What you Get】You will get 1*Pi 5 8GB Single Board,1*RasTech Case,1*Active Cooler,1*Screwdriver,1*Installation instructions,12-month free warranty, lifetime service, 24-hour prompt and friendly response.
- 【More Connectors】There are two USB 3.0 ports(5Gbps simultaneously) and two USB 2.0 ports, which triple total bandwidth ,support any combination of up to two cameras or displays. Peak SD card performance is doubled through support for the SDR104 high-speed mode. It provides a smooth desktop experience for you. Offer Gigabit Ethernet and a PCIe interface, along with dual-band Wi-Fi and Bluetooth 5.0/BLE wireless capability. The RasTech Pi 5 Kit use the new 27W 5.1V 5A USB-C power connector.
- 【 Support Dual 4Kp60 Display 】Each of the two microHDMI sockets can control a 4K display at 60 Hertz, now support HDR, offering super HD video for media streaming projects. RPi 5 is the first RPi model that comes with a PCI Express port (PCIe 2.0 x1 with 500 MB/s) to attach SSDs (requires separate M.2 HAT).
- 【 Excellent Chips And Applications】Pi 5 is a full-size Pi computer using silicon built in-house at Pi. The RP1 “southbridge” provides the bulk of the I/O capabilities for Pi 5. Pi 5 is more friendly and convenient in the development of Internet of Things, Web development, machine identification, automatic control and other electronic equipment applications and network.
- 【 Faster CPU, Better GPU 】 Pi 5 features a Broadcom BCM2712 64-bit quad-core Arm Cortex-A76 processor running at 2.4GHz, it delivers a 2–3× increase in CPU performance relative to RaspberryPi 4. The 800MHz VideoCore VII GPU is compatible to OpenGL ES 3.1 and Vulkan 1.2, substantial uplift in graphics performance. Pi 5 Offers lightning-fast CPU speed, a PCI Express interface, a Real Time Clock (RTC) and a power button and runs significantly cooler than Pi 4.
Check the effective, not merely intended, configuration
It is easy to edit a template, disabled site, or pool file that is not included. Follow the include chain used by the running services and look for duplicate server blocks, duplicate pools, or a later directive overriding the value you changed. Compare the endpoint shown in the error line with the endpoint in the files: that is a quick way to detect that Nginx is still using an older or different configuration.
When a package upgrade changes the PHP version, socket filenames commonly change with it. Nginx may continue pointing at the previous version even though the new FPM service is healthy. Treat the version in a filename such as php8.2-fpm.sock as part of the endpoint, not as a cosmetic label.
Fix a mismatched Unix-socket path
For a Unix socket, Nginx uses the form:
fastcgi_pass unix:/run/php/php8.3-fpm.sock;
The corresponding pool might contain:
listen = /run/php/php8.3-fpm.sock
The path must match character for character, including the PHP version in the filename. A common failure is that the pool creates /run/php/php8.2-fpm.sock while Nginx still points to /run/php/php8.3-fpm.sock. Another is editing a pool file that is not loaded, while a different pool or include supplies the active value.
Quick wins for a faster PC:
Scan for outdated or missing drivers - takes under a minuteDriver Scan →Clear out junk files and repair common Windows errorsFree Scan →After correcting the endpoint:
- Run
sudo nginx -tto catch Nginx syntax errors. - Reload Nginx with
sudo systemctl reload nginx. - Restart or reload the matching FPM unit so it recreates the socket with the new setting, for example
sudo systemctl restart php8.3-fpm. - Confirm the socket now exists, then reproduce the request while following the error log.
Socket filenames and service names are distribution-specific examples, not universal names. Use the values present on your installation. A socket that disappears after an FPM restart is not evidence that Nginx is wrong; it usually means FPM failed to recreate it, so the journal is the next place to look.
Repair “permission denied” safely
A present socket can still produce errno 13. Linux checks both the socket’s ownership and mode and the execute (search) permission on every parent directory. Inspect the result:
ls -l /run/php/php8.3-fpm.sock
stat /run/php/php8.3-fpm.sock
namei -l /run/php/php8.3-fpm.sock
The FPM pool controls Unix-socket access with:
listen.owner = www-data
listen.group = www-data
listen.mode = 0660
www-data is only an example. Set the owner or group so the account running Nginx workers can connect. Determine that account from your Nginx configuration and service definition; do not assume it is the same on every distribution.
- Owner and group: The Nginx worker must be the owner or a member of the socket’s group, according to the mode bits.
- Mode: A restrictive 0660-style mode permits the owner and group while denying unrelated users. Use the distribution’s documented default where possible.
- Directory traversal: The Nginx account needs search permission on
/run,/run/php, and any custom parent directory, even if the socket itself looks correct. - Socket recreation: FPM applies these settings when it creates the socket. Restart the pool after changing them; changing a configuration file does not alter an already-created socket.
If Nginx and FPM run under different users, a shared group or a narrowly scoped ACL is safer than making the socket world-writable. Do not use 0777 or an equivalent permissive setting as a shortcut. After restarting FPM, verify ownership and mode again and test one request. If permissions revert, the socket is being recreated by FPM with values from another active pool or included configuration, so trace which pool owns the endpoint.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Rank #3
- Pi5 8GB Pack: RasTech Pi 5 8GB kit includes 1 x Pi5 8GB board ,1 x 64GB Card, 2 x Card Readers,1 x Active Cooler,1 x Case for Pi5, 2 x 4K Micro HD Out Cable,1 x GaN 27W 5A USB-C Power supply,1 x Screwdriver and 1 x instructions.
- Pi5 8GB Board: The Pi5 board is equipped with a 64-bit quad-core Arm Cortex-A76 processor running at 2.4GHz and an 800MHz VideoCore VII GPU with support for OpenGL ES 3.1 and Vulkan 1.2, which delivers a significant increase in graphics performance. Dual HD Out 4Kp60 display outputs and a built-in dual 4-channel MIPI camera/display transceiver provide state-of-the-art camera support. The Pi 5 offers a 2-3 times increase in CPU performance compare to Pi4.
- Important Graphics Features: Equipped with an 800MHz VideoCore VII GPU and providing better graphics performance, suitable for multimedia applications,gaming,and graphics intensive tasks.Provides 1 UART interface,1 card slot that supports high-speed operation, 2 USB. 3 0.5 ports that support synchronous 0Gbps operation,2 USB 2.0 port ports,2 4Kp60 display outputs that support HDR.Built-in dedicated dual 4-channel 1Gbps MIPI DSI/CSI connectors,triple the total bandwidth.
- Cooling Kit for Pi 5: Compatible with Active Cooler for Raspberry Pi5, It can provide Pi 5 board with better cooling effect in using. The Case can accurately access usb-c power jack,Micro HD Out ports, usb ports, Ethernet jack, card slot, power button, 4-lane MIPI DSI/CSI connectors and so on, and it also supports installation of cooling fan.
- 64GB Card Kit and GaN 27W USB-C Power Supply: With extra 64GB card to store more files and card readers for multiple medium, keep better performance for Raspberry Pi 5, 27W USB C Power Supply is Compatible with Pi5 8GB, offers a variety of output voltage options, including 5.1V at 5A, 9.0V at 3.0A, 12.0V at 2.25A, and 15.0V at 1.8A, providing for different device requirements.
When the endpoint uses TCP instead of a Unix socket
A pool can listen on an address such as 127.0.0.1:9000, with Nginx configured accordingly:
listen = 127.0.0.1:9000
fastcgi_pass 127.0.0.1:9000;
For TCP, “connection refused” usually means no process is listening on that address and port, the pool failed to start, or the two configurations use different ports or interfaces. Check the listener with tools available on your system, then inspect FPM’s status and journal. A port bound only to loopback will not accept connections sent to another interface.
Use TCP deliberately when Nginx and FPM are separated by a host or container boundary. On the same host, a Unix socket normally provides a smaller network attack surface and avoids exposing a FastCGI port. If TCP is required, bind it to a private interface and restrict which clients may connect.
| Consideration | Unix socket | TCP endpoint |
|---|---|---|
| Typical locality | Processes on the same host | Same host or separate host/container |
| Access control | Filesystem owner, group, mode, directory permissions, or ACL | Bind address, firewall, and PHP-FPM client restrictions such as listen.allowed_clients |
| Typical failure clues | Missing path or permission-denied errno | Connection refused, wrong address, blocked port, or unreachable host |
| Operational trade-off | Simple local path, but runtime-directory and ownership issues matter | Useful across boundaries, but requires network isolation and additional connectivity checks |
Do not switch from a socket to TCP merely to bypass a permission error. That changes the security boundary and can expose FPM to clients that should never reach it. Correct the filesystem ownership or deliberately design the private network path instead.
Diagnose timeouts and an exhausted FPM pool
If the log says upstream timed out, do not immediately increase the timeout. Nginx’s fastcgi_read_timeout measures the interval between successive reads from FastCGI, not the total lifetime of a response. Its documented default is 60 seconds. A longer value can hide a saturated pool or a stuck application while tying up Nginx connections for longer.
Expose the PHP-FPM status page only to administrators, then inspect these counters:
listen queue: requests currently waiting for an FPM worker.max listen queue: the highest observed queue depth since the pool started.active processesandidle processes: current worker utilization.max children reached: whether the pool has hit its configured worker ceiling.
pm.max_children is the hard cap on simultaneous FPM workers. A nonzero max children reached together with a growing queue indicates contention, but raising the limit without measuring memory and CPU can trigger swapping and create more failures.
Rank #4
- CanaKit Raspberry Pi 5 Essentials Starter Kit
A safer capacity-tuning sequence
- Record queue depth, active and idle workers, and
max children reachedduring the incident. - Measure memory use and CPU per PHP worker, and account for the rest of the host’s services.
- Check the application, database, filesystem, and external-service latency that keeps workers busy.
- Choose the FPM process mode deliberately:
dynamic,ondemand, orstaticeach changes how workers are created and retained. - Adjust
pm.max_childrenonly when the host has enough headroom, then observe queue and latency metrics after the change.
When a request legitimately performs long work, raise fastcgi_read_timeout only for the affected location and only after confirming that capacity and application behavior are understood. Fix slow code or move long-running work to an asynchronous job where appropriate; a timeout increase alone does not make a blocked worker available.
A queue with idle processes suggests a different problem from a queue with every worker active. In the former case, revisit the endpoint, permissions, or request routing; in the latter, investigate worker duration and resource limits. Compare the counters during a failing request rather than relying on a single snapshot after traffic has subsided.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Use deeper logging only for the incident
Set error_log at an appropriate severity for the affected server or location when the normal log lacks enough context. Nginx debug logging requires a binary built with debug support and an error_log directive using the debug level. Enable it temporarily, reproduce one failure, save the relevant lines, and return to the normal level to avoid excessive logs and overhead.
At the same time, inspect the PHP-FPM pool log and the system journal. Look for configuration parse errors, failed socket creation, fatal PHP errors, worker crashes, process limits, out-of-memory events, and clean or forced worker exits. Nginx can have a perfectly valid configuration while FPM repeatedly fails to start. Correlate timestamps across both logs: the first FPM error often explains the later Nginx 502.
Keep the FastCGI boundary private
PHP’s documentation warns that PHP-FPM must not be reachable from an untrusted network. A hostile FastCGI client can control request configuration, including settings such as auto_prepend_file, and may be able to execute arbitrary code.
Free tools Windows power users keep installed
One-click scans. No signup required.
- Prefer a Unix socket when Nginx and FPM share a host.
- If using TCP, bind FPM to a private interface rather than a publicly reachable address.
- Use firewall rules and, where supported,
listen.allowed_clientsto limit callers. - Do not expose an FPM status endpoint publicly; restrict it to administrators.
- Keep socket modes and directory permissions as narrow as the deployment allows.
A practical recovery checklist
- Capture a fresh Nginx error-log line while reproducing one failed PHP request.
- Classify the failure as missing endpoint, refused connection, permission denial, timeout, or upstream close.
- Check the actual FPM service status and journal for the installed PHP version.
- Read the active pool’s
listenvalue and compare it exactly with Nginx’sfastcgi_pass. - For Unix sockets, inspect the socket and every parent directory with
ls,stat, andnamei. - Correct
listen.owner,listen.group, andlisten.mode; restart FPM so the socket is recreated. - For TCP, verify the address, port, listener, firewall, and allowed-client restrictions.
- Use the FPM status counters to distinguish slow application work from a worker-capacity ceiling.
- Run
nginx -t, reload Nginx, restart or reload the matching FPM unit, and retest. - Restore normal logging and keep the FastCGI endpoint private after the incident.
Frequently Asked Questions
Why is Nginx returning 502 Bad Gateway for PHP requests?
The error can mean a missing Unix socket, a refused TCP or socket connection, insufficient socket permissions, a timeout while PHP works, or an upstream process that closed early. Capture the exact Nginx error-log line and errno before changing settings.
How do I fix connect() to unix:/run/php/php-fpm.sock failed?
Read the active PHP-FPM pool’s listen value and compare it character for character with Nginx’s fastcgi_pass. If the log says “No such file or directory,” confirm FPM is running and that the parent directory and socket are created. Restart the matching FPM unit after correcting the path.
Best Value
- Includes Raspberry Pi 5 16GB with 2.4Ghz 64-bit quad-core CPU (16GB RAM)
- Includes 128GB Micro SD Card pre-loaded with 64-bit Raspberry Pi OS, USB MicroSD Card Reader
- CanaKit Turbine Black Case for the Raspberry Pi 5
- CanaKit Low Noise Bearing System Fan
- Mega Heat Sink - Black Anodized
Why does nginx -t pass while PHP still returns 502?
The syntax test validates Nginx’s own configuration only. It does not check whether PHP-FPM is running, whether the socket exists, whether permissions allow access, or whether a TCP listener accepts connections. Reload Nginx, then test the FPM service and endpoint separately.
How do I fix PHP-FPM socket permission denied?
Check the socket owner, group, mode, and every parent directory’s search permission. Set the pool’s listen.owner, listen.group, and restrictive listen.mode so the Nginx worker can connect. Restart FPM to recreate the socket, and use a shared group or narrow ACL rather than world-writable permissions.
Should I use a Unix socket or TCP for Nginx and PHP-FPM?
Use a Unix socket when both processes share a host and you can manage filesystem permissions. Use TCP for a deliberate host or container boundary, binding it to a private interface and restricting allowed clients. Do not expose FPM to an untrusted network.
What does an FPM listen queue mean?
It is the number of requests waiting for an available FPM worker. Compare listen queue, max listen queue, active and idle processes, and max children reached. A growing queue with the worker ceiling reached indicates saturation; raise pm.max_children only after measuring memory and CPU headroom.
Should I increase fastcgi_read_timeout to stop 502 errors?
Only after confirming that the application legitimately needs more time and that the pool is not saturated. The setting controls the interval between successive reads, with a documented 60-second default, not the total response lifetime. Increasing it can keep connections occupied while a stuck worker remains unavailable.
Why does a permission fix disappear after restarting PHP-FPM?
FPM applies socket ownership and mode when it creates the socket. If the values revert, another active pool or included configuration may control that endpoint. Recheck the effective pool configuration, restart the correct unit, and verify the recreated socket with stat or ls -l.
The Bottom Line
Read the exact Nginx error first, then match the active FPM listen endpoint to fastcgi_pass. Repair socket ownership and directory access without weakening permissions, use FPM queue counters before raising worker or timeout limits, and keep any FastCGI TCP endpoint private.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

