How to Fix a 502 Bad Gateway in WordPress
errors
When the web server reported a bad gateway error, a reverse proxy received no usable response from the upstream service it was trying to reach. In WordPress, nginx, Traefik, a CDN edge, or a load balancer may be waiting on PHP-FPM or an application container. A 502 identifies the broken proxy-to-upstream exchange, but logs are needed to distinguish a crashed process, exhausted worker pool, incorrect endpoint, restart, or invalid upstream response.
Why This Happens
PHP-FPM crashed or was killed
A PHP-FPM child can exit because of a fatal process failure or severe memory pressure. At the container or host level, the kernel or orchestrator may kill a process that exceeds available memory. A plugin or theme that retains excessive data, an unexpectedly large request, and several memory-heavy workers running together can all contribute.
PHP's memory_limit and a container memory limit are separate boundaries. A PHP allocation error may be logged by PHP, while a container-level kill can terminate the process before it returns a valid FastCGI response.
The PHP-FPM pool is exhausted
With a process manager configuration such as pm = dynamic, pm.max_children limits how many requests the pool can serve concurrently. When every child is busy, new requests wait. Enough queueing can cause nginx or another proxy to time out, particularly when slow database queries or external API calls hold workers.
Raising pm.max_children without measuring memory per worker is risky. More children may exceed host or container capacity and turn queueing into out-of-memory restarts.
The upstream address or protocol is wrong
nginx may send FastCGI traffic to a socket that does not exist or a TCP port where nothing is listening. In containers, a Kubernetes Service can select the wrong pods, map to the wrong targetPort, or reference pods that are not ready. A proxy configured for HTTP cannot communicate correctly with a raw FastCGI listener.
Configuration that looks correct in one environment may fail after a port, socket path, service name, or container layout changes.
Backends are restarting or unhealthy
A deployment can replace the application while requests are active. If readiness is marked too early, the proxy may send traffic before PHP-FPM and WordPress dependencies are ready. If termination is too abrupt, in-flight responses disappear. Failed health checks can also remove every backend and leave the load balancer with nowhere to route.
The upstream returned an invalid response
A broken FastCGI exchange, truncated headers, or an application server speaking the wrong protocol can produce an invalid response. This is different from an ordinary WordPress error page, which is still a valid HTTP response and would not normally require the gateway to invent a 502.
Diagnosing the Failed Hop
Start at the layer that displayed or logged the 502, then follow its configured upstream.
-
Read the proxy error log around the exact timestamp. nginx messages such as
connect() failed,upstream sent invalid header, orno live upstreamspoint to different failure classes. Also note the upstream address recorded in the message.tail -n 200 /var/log/nginx/error.logA refused connection suggests no listener at that endpoint. A timeout suggests a listener that did not respond in time. An invalid header suggests a protocol or application-response problem.
-
Check PHP-FPM service and error logs for child exits, pool saturation, allocation failures, and restart loops. Inspect system logs for out-of-memory kills. Do not assume increasing PHP's memory setting repairs a container or host that has no memory available.
-
In Kubernetes, inspect pod state, restarts, termination reason, events, Service selectors, and endpoints:
kubectl get pods kubectl describe pod wordpress-abc123 kubectl get service wordpress kubectl get endpoints wordpressReplace resource names with those in the deployment.
OOMKilledas a previous termination reason supports a memory diagnosis, while empty endpoints suggest selector or readiness failure. Events may have expired, so combine them with centralized logs and metrics. -
Verify what is actually listening from the proxy's network context:
ss -lnt test -S /run/php/php-fpm.sockCompare the result with
fastcgi_pass,proxy_pass, the ServiceportandtargetPort, and the container's listener. Test an HTTP health route only when the upstream actually speaks HTTP. -
Correlate failures with deployments, traffic spikes, plugin changes, PHP-FPM queue depth, memory use, and health-check state. Intermittent 502s during load often require time-series evidence rather than a single successful request.
This differs from an nginx 499 client-closed request: a 502 is a gateway failing to obtain a valid upstream response, while a 499 records the client abandoning nginx first.
Fixing Each Cause
Repair memory failures
Identify the process and request consuming memory. Profile or disable the responsible plugin in a controlled way, fix unbounded loops or data loads, and process large datasets in batches. Then right-size PHP and container memory limits together. Merely raising limits can postpone another failure if the code continues to grow without bound.
Restore a stable version from a known backup when a deployment introduced the problem. WordPress support can help isolate plugin or theme behavior without treating infrastructure symptoms as the root cause.
Size the PHP-FPM pool from measurements
A pool might include settings like:
pm = dynamic
pm.max_children = 12
pm.start_servers = 3
pm.min_spare_servers = 2
pm.max_spare_servers = 5
These are illustrative values, not defaults or recommendations. Choose them from available memory, observed worker size, concurrency, and latency. Reduce slow request duration as well as tuning capacity, then monitor queueing and worker saturation under representative traffic.
Correct upstream routing
Make the proxy protocol, hostname, port, and socket agree with the running service:
location ~ \.php$ {
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_pass unix:/run/php/php-fpm.sock;
}
Validate nginx configuration before reloading it. In Kubernetes, correct Service selectors and targetPort, and verify that ready endpoints appear. Avoid routing a public proxy directly to a transient pod address when a stable Service is intended.
Improve readiness and deployments
Make readiness checks represent the minimum dependencies required to serve traffic, without turning every optional dependency into a reason to remove all backends. Allow startup time before readiness succeeds. During termination, stop new traffic, allow in-flight work a bounded grace period, and use rolling updates that retain enough ready capacity.
On managed WordPress hosting, coordinated ingress, process, and deployment configuration helps keep these layers from drifting independently.
Treat timeouts as a budget
Adjust proxy or FastCGI read timeouts when a valid operation is expected to take longer, but first establish why. A larger timeout does not fix a dead listener, invalid protocol, leaking plugin, or exhausted pool. Keep interactive requests bounded and move long work to background jobs where practical.
Preventing Another 502
Alert on PHP-FPM queueing, child exits, container restarts, out-of-memory events, empty upstream pools, and elevated gateway errors. Test Service and port changes before rollout, use readiness probes, and preserve capacity during deployments. Review plugin changes for memory and latency regressions, and keep recoverable daily backups as part of WordPress maintenance.
How Nova Handles This
Nova manages the OpenLiteSpeed application layer behind Traefik ingress in tenant-isolated Kubernetes namespaces, with readiness-aware routing and daily GCS backups supporting diagnosis and recovery.
FAQ
Is a 502 always caused by PHP-FPM?
No. PHP-FPM is a common WordPress upstream, but a CDN, load balancer, application container, network path, or incorrect proxy configuration can fail in the same way. Follow the upstream address in the gateway log.
Will restarting PHP-FPM fix the error?
It may restore service temporarily if workers are stuck or unavailable. Review the logs and resource history after restarting, because a memory leak, slow plugin, or pool-sizing problem will often recur.
Is increasing pm.max_children safe?
Only after measuring memory per worker and available capacity. Too few children can cause queueing, while too many can exhaust memory and produce more restarts. Tune the pool together with slow application work.
What is the difference between 502 and 504?
A 502 means the gateway received no valid upstream response, which includes connection and protocol failures. A 504 generally means the gateway waited for the upstream past its deadline. Actual proxy behavior can vary, so use its error log for the decisive cause.
See What's Included With Nova Managed Hosting
Nova runs every managed WordPress tenant in an isolated Kubernetes namespace with daily automated backups and managed core/plugin updates. If you're troubleshooting a specific issue on your own site, our team can help.