Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Scan for outdated or missing drivers - takes under a minute3Clear out junk files and repair common Windows errorsA 502 from Nginx usually means Nginx could not complete a connection to PHP-FPM. Read the Nginx error-log line produced by one failing request, then compare the PHP-FPM pool’s listen endpoint with Nginx’s fastcgi_pass. That evidence tells you whether the socket is missing, refusing connections, blocked by permissions, or timing out. A passing nginx -t only proves that Nginx can parse its configuration; it does not prove that PHP-FPM is running or that its socket can be reached.
Need a server to try this on? Antihost offers Linux VPS plans with NVMe storage, full root access and a 14-day free trial.
What a 502 means in an Nginx/PHP-FPM stack
In a typical Linux deployment, a browser sends a request to Nginx, Nginx passes PHP work to PHP-FPM through a Unix socket or TCP endpoint, and PHP-FPM returns the response. A 502 Bad Gateway means the gateway (Nginx) could not obtain a valid response from that upstream. The HTTP status is only a symptom; the exact reason is in Nginx’s error log.
As an Amazon Associate I earn from qualifying purchases.
Do not start by changing random timeout values or making a socket world-writable. Capture one failure, read the errno and upstream address, and make the smallest change that addresses that message. Socket filenames and service names include the installed PHP version and distribution conventions, so examples such as /run/php/php8.3-fpm.sock are illustrative rather than universal.
First step: capture the exact error
Open a shell, reproduce one failing PHP request, and watch the configured Nginx error log:
#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
sudo tail -n 100 /var/log/nginx/error.log
Your system may use a different path. Nginx writes messages at the closest applicable error_log level, and the active path can be found in the server, location, or main configuration (and, when necessary, from the build configuration). Record the complete line, including the upstream endpoint and errno number. That one line normally determines the next check.
“No such file or directory”
A message such as connect() to unix:/run/php/php-fpm.sock failed (2: No such file or directory) means the configured Unix-socket path did not exist when Nginx handled the request. Common causes are a stopped PHP-FPM service, a pool that creates a differently named socket, or a stale PHP-version path in the Nginx server block.
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 →- Confirm that the FPM service is running.
- Read the pool’s active
listen = ...value. - Check whether that exact path appears on disk after FPM starts.
“Connection refused”
connect() failed (111: Connection refused) means the selected TCP port or Unix socket is present but not accepting connections. Check for an FPM startup failure, a crashed service, a wrong port, or a mismatch between the pool and Nginx configuration. A socket file can remain briefly after its owning process has stopped; its presence alone does not prove that FPM is listening.
“Permission denied”
connect() ... failed (13: Permission denied) means Nginx found the socket but its worker account could not open it. Inspect the socket owner, group, mode, and every parent directory’s execute (search) permission. Then compare those values with the pool’s listen.owner, listen.group, and listen.mode settings.
“Upstream timed out”
An upstream timed out entry points to a response-read timeout or a PHP-FPM worker that is taking too long. Nginx’s fastcgi_read_timeout measures the interval between successive reads from the upstream, not the total lifetime of the request. Investigate slow application work and FPM capacity before raising it. The module documentation defines a 60-second default; treat that as a configuration default, not a performance guarantee.
“Upstream prematurely closed” or “recv() failed”
These messages indicate that PHP-FPM or the application closed or reset the connection before Nginx received a complete response. Inspect the PHP-FPM log and system journal for fatal errors, worker exits, crashes, memory pressure, or request-specific failures. Nginx’s line is authoritative for what it observed, while the FPM log usually explains why the upstream disappeared.
Why nginx -t can pass while PHP still returns 502
Run:
sudo nginx -t
This checks whether Nginx can parse its configuration and start its configuration test successfully. It does not open the PHP-FPM socket, connect to a FastCGI port, verify that the FPM unit is running, or execute a PHP request. As an Nginx developer has explained, upstream reachability matters when a request is processed, not when Nginx parses its configuration.
Use the test before a reload to catch syntax errors, but treat it as only one checkpoint. A complete validation also requires a healthy FPM service, matching endpoints, usable permissions, and a successful request while the error log is being watched.
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.
Verify PHP-FPM and the endpoint
Find the installed FPM unit
Service names vary by distribution and PHP version. Start with the unit that exists on the host rather than copying a version-specific example:
systemctl --type=service | grep -i fpm
systemctl --failed
sudo systemctl status php8.3-fpm
sudo journalctl -u php8.3-fpm --no-pager -n 100
Replace php8.3-fpm with the actual unit name. The journal can reveal a syntax error in a pool file, a missing directory, a failed module load, a resource limit, or an immediate worker exit. If the service is inactive or failed, fix that startup problem first; Nginx cannot compensate for an FPM process that never started.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Compare listen and fastcgi_pass
Every PHP-FPM pool must define a FastCGI acceptance address with listen. In the Nginx server block, fastcgi_pass must identify the same Unix socket or TCP endpoint. Typical pool files are under /etc/php/<version>/fpm/pool.d/, although layouts differ.
| Connection type | PHP-FPM pool setting | Nginx setting | What must match |
|---|---|---|---|
| Unix socket | listen = /run/php/php8.3-fpm.sock |
fastcgi_pass unix:/run/php/php8.3-fpm.sock; |
The complete filesystem path, including the PHP-version filename |
| TCP | listen = 127.0.0.1:9000 |
fastcgi_pass 127.0.0.1:9000; |
The same address and port, with FPM actually bound there |
Compare the active files, not an example copied from a different release. A common failure is Nginx pointing at /run/php/php-fpm.sock while the pool creates /run/php/php8.3-fpm.sock. Another is editing one pool while Nginx is routed to a different pool.
After correcting the endpoint, test and apply both sides deliberately:
- Run
sudo nginx -t. - Reload Nginx with your distribution’s service command, for example
sudo systemctl reload nginx. - Restart or reload the matching FPM unit so it recreates the intended socket or rebinds the intended port.
- Make one PHP request while following the error log.
A successful configuration test at step one still does not establish socket reachability; the request at step four is the proof.
Repair Unix-socket permissions without weakening security
When the error is permission-related, set the pool’s socket ownership and mode so the Nginx worker account can connect. PHP-FPM provides these Linux controls:
listen.owner = nginx-worker-user
listen.group = web-runtime
listen.mode = 0660
Use the actual Nginx worker user and an appropriate shared group for your host. A distribution may choose a different account or a documented 0660-style default. Do not assume that the account running the master process is the account opening the socket; check the Nginx configuration and running processes.
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.
Check the socket and directory traversal
ls -l /run/php/php8.3-fpm.sock
stat /run/php/php8.3-fpm.sock
namei -l /run/php/php8.3-fpm.sock
The socket’s owner and group must grant the Nginx worker read/write access according to the operating system’s Unix-socket rules. Every parent directory must also allow that account to traverse it. A correct socket mode cannot overcome a parent directory that denies search permission.
Use a group or narrowly scoped ACL
If Nginx and FPM run under different users, put the required accounts in a dedicated shared group or apply an ACL granting only the needed access. Recreate the socket by restarting FPM after changing pool directives, then verify with stat or ls -l. Avoid chmod 777 or a world-writable socket: it lets any local account attempt to send FastCGI requests.
Free tools Windows power users keep installed
One-click scans. No signup required.
If permissions revert after every restart, the pool configuration is the source of truth. Fix listen.owner, listen.group, or listen.mode there instead of applying a temporary command to the current socket.
Investigate load, queueing, and timeouts
A healthy endpoint can still produce 502s or long waits when all FPM workers are occupied. Expose the FPM status page only to administrators, then inspect these counters:
- listen queue: requests currently waiting for a worker.
- max listen queue: the highest observed queue length.
- active processes: workers currently handling requests.
- idle processes: workers available for work.
- max children reached: whether the configured worker ceiling has been hit.
pm.max_children is the hard cap on simultaneous FPM workers. If max children reached is nonzero while the listen queue grows, measure memory and CPU use per worker before increasing the cap. More workers can consume all available RAM, trigger swapping, and create more failures instead of removing the bottleneck.
Choose a process manager deliberately
PHP-FPM supports dynamic, ondemand, and static process modes. The right mode depends on traffic shape and memory headroom: a bursty site may benefit from workers created on demand, while a steady workload may keep a predictable pool warm. Tune the mode and its related limits from observed queue depth, latency, and resource use rather than from the 502 count alone.
Raise fastcgi_read_timeout only for legitimate slow work
Increasing the timeout can hide a slow query, external API call, or exhausted pool. First identify whether PHP is making progress and whether workers are queued. If the application legitimately needs a longer pause between response chunks, set fastcgi_read_timeout in the relevant Nginx context, test the configuration, and monitor resource usage. Remember that the directive controls the gap between reads, not an absolute total-response limit.
Increase diagnostic visibility temporarily
Check both sides of the boundary:
- Nginx’s configured
error_logfor endpoint, errno, timeout, and upstream-close messages. - The PHP-FPM pool log and
journalctlfor startup failures, fatal PHP errors, worker exits, crashes, and resource-limit messages. - The application log for a request that consistently triggers a premature close or long execution time.
If ordinary logging does not distinguish the failure, raise error_log to an appropriate level for the affected server or location. Nginx debug logging requires a binary built with debug support and the debug parameter on error_log. Enable it briefly, reproduce one failure, collect the relevant lines, and restore the normal level; leaving debug logging enabled can generate excessive sensitive output and disk usage.
Rank #4
- CanaKit Raspberry Pi 5 Essentials Starter Kit
Unix socket or TCP: choose the boundary that fits the deployment
For Nginx and PHP-FPM on the same host, a Unix socket is usually the simplest boundary. A separate host or container may require TCP, but the network endpoint must be private and explicitly restricted.
| Decision axis | Unix socket | TCP endpoint |
|---|---|---|
| Locality | Best suited to processes sharing a filesystem and host | Useful across a host, container, or other network namespace |
| Access control | Filesystem owner, group, mode, directory permissions, and optional ACLs | Bind to a private interface and restrict permitted clients |
| Typical failure evidence | Missing path, refused connection, or filesystem permission denial | Refused connection, wrong address/port, firewall or bind mismatch |
| Operational trade-off | Requires correct socket lifecycle and directory permissions | Requires network exposure controls and clearer isolation boundaries |
PHP warns that an untrusted FastCGI client can control request configuration, including settings such as auto_prepend_file, and can thereby execute arbitrary code. Keep FPM local or tightly restricted. If TCP is necessary, bind it to a private interface, limit allowed clients with the pool’s access controls where available, and ensure no untrusted network can reach the port.
Common configuration mistakes that survive a reload
Some fixes appear correct but do not affect the request that is failing. First, confirm that the edited Nginx server block is the one selected for the hostname and URI; a different virtual server or location may contain another fastcgi_pass. Second, confirm that the edited FPM pool is the pool serving that endpoint. Multiple pools can use different socket names, users, groups, and limits.
Also check the complete path character by character. A missing PHP-version suffix, a typo in /run, or a socket placed in a directory that is recreated at boot can produce the same “No such file or directory” message. If a restart changes the socket owner or mode, the persistent pool directives—not a one-time chmod—must be corrected. If the service starts and then stops, focus on the FPM journal rather than repeatedly reloading Nginx.
Use a controlled change sequence
- Save the current Nginx and pool settings so the last-known configuration is recoverable.
- Change one endpoint, ownership, or capacity setting at a time.
- Run
nginx -tbefore reloading Nginx. - Restart or reload FPM when a pool setting must recreate a socket.
- Reproduce one request and compare the new error-log line with the old one.
- Remove temporary debug verbosity after collecting evidence.
This sequence prevents a reload from masking which change fixed the problem and limits the time that diagnostic logging or a broader access rule remains active.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.A concise recovery runbook
- Reproduce once: request the failing PHP URL while watching the Nginx error log.
- Classify the line: distinguish missing socket, refusal, permission denial, timeout, or premature upstream close by its errno and wording.
- Check FPM health: inspect the installed unit with
systemctl status, failures withsystemctl --failed, and details withjournalctl -u <fpm-unit>. - Compare endpoints: read the active pool
listenand the server block’sfastcgi_pass; make them identical for the selected transport. - Validate safely: run
nginx -t, reload Nginx, and restart or reload the matching FPM pool so the endpoint is recreated. - Fix access: for a Unix socket, set matching
listen.owner,listen.group, and restrictivelisten.mode; verify parent-directory traversal. - Check saturation: review FPM queue and process counters, then tune
pm.max_childrenonly with measured memory and CPU headroom. - Handle genuine slow work: inspect the application before changing
fastcgi_read_timeout; increase it only when a longer interval between reads is justified. - Retest and clean up: confirm a successful request, return temporary debug logging to normal, and keep the FPM endpoint inaccessible to untrusted clients.
What to record if the error returns
Keep the exact Nginx line, timestamp, requested URL, upstream path or address, FPM unit status, and the relevant FPM journal entries. Note whether the socket existed, its owner/group/mode, queue counters, and whether the failure affected every PHP request or only one application route. This record separates configuration drift from load-related saturation and from application-specific crashes, making the next incident faster to resolve.
Recommended Free Tools
Frequently Asked Questions
Why does Nginx return 502 when the socket file exists?
A socket file can remain after PHP-FPM stops, so existence does not prove that a process is accepting connections. Check the FPM unit and journal, then reproduce the request. A refusal usually indicates that the endpoint is present but not accepting connections.
Why does nginx -t pass but PHP still returns 502?
The test validates Nginx syntax and startup configuration only. It does not connect to PHP-FPM, verify the service, check socket permissions, or execute a PHP request. Validate the endpoint and make a real request while watching the error log.
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
How do I fix “No such file or directory” for a PHP-FPM socket?
Compare the pool’s active listen path with Nginx’s fastcgi_pass unix: path, including the PHP-version suffix. Confirm FPM is running and recreates that exact path after restart.
How do I fix PHP-FPM socket permission denied?
Set listen.owner, listen.group, and a restrictive listen.mode that grants the Nginx worker access. Check every parent directory’s search permission, restart FPM to recreate the socket, and verify with stat or ls -l. Do not use a world-writable socket.
The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Should I switch from a Unix socket to TCP to solve 502 errors?
Not automatically. Use a Unix socket for same-host processes when filesystem permissions are manageable. Use TCP for separate hosts or network namespaces only when you can bind it privately and restrict clients; an exposed FastCGI endpoint is a serious security risk.
What does an upstream timeout mean?
It means Nginx waited too long between reads from the upstream, often because PHP work is slow or all workers are busy. Inspect application latency, FPM queue counters, and worker capacity before increasing fastcgi_read_timeout. The directive is an interval between reads, not a total-request timer.
What FPM counters show pool saturation?
Review listen queue, max listen queue, active processes, idle processes, and max children reached on the status page. A growing queue together with a nonzero maximum-children counter indicates that the pool reached its concurrency ceiling.
How should I raise pm.max_children safely?
Measure memory and CPU consumed per worker first. Increasing pm.max_children without headroom can cause swapping and more failures. Change the limit deliberately, observe queue and latency counters, and keep the status endpoint restricted to administrators.
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 minutePC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11What should I check after changing socket permissions?
Restart or reload the matching FPM unit so the socket is recreated, then inspect its owner, group, and mode and verify directory traversal. Reload Nginx only after nginx -t succeeds, and make one request while following the error log.
What should I do when PHP-FPM closes the connection early?
Treat upstream prematurely closed or recv() failed as evidence that the upstream closed or reset the connection. Check the FPM log, journal, and application log for fatal errors, worker exits, crashes, resource limits, or a request-specific failure.
The Bottom Line
Start with one exact Nginx error-log line, then verify that PHP-FPM is running and that its listen endpoint exactly matches Nginx’s fastcgi_pass. Repair Unix-socket ownership and directory access without making the socket public, inspect FPM queue counters before raising worker limits, and change fastcgi_read_timeout only for measured slow work. Keep TCP FastCGI endpoints private, validate with a real request, and return temporary debug logging to normal.
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.




