Short answer: An nginx 502 Bad Gateway error means nginx could not get a valid response from the upstream it proxies to, usually PHP-FPM or a Node.js, Python or Go app. To fix it, read /var/log/nginx/error.log: it names the upstream and the reason, most often a stopped service, a wrong socket path, a permission problem or an oversized header.

Key takeaways

  • RFC 9110 defines 502 as a response from a server acting as a gateway or proxy that received an invalid response from an inbound server.
  • This is the classic WordPress and Laravel 502.
  • Error 13 means the socket exists but the nginx worker user, usually www-data on Ubuntu and Debian or nginx on RHEL-based systems, cannot open it.
  • For reverse proxies to Node.js, Python, Go or another server, error 111 means nothing is listening where nginx expects it.

I run and fix a lot of small VPS servers with nginx in front of WordPress, Laravel and Node apps, and the 502 is the error I see most after migrations and upgrades. This guide follows the order I use in practice: read the log, match the message to a cause, apply the specific fix, then test. Every command is for Ubuntu or Debian with systemd, but the logic is the same everywhere.

nginx 502 bad gateway troubleshooting flow: read the log, check the upstream, fix the socket or port, test and reload
Troubleshooting flow for an nginx 502 bad gateway error, from the error log line to the upstream fix and a safe reload.

From my own work: When a client messages me that the site shows 502, I do not touch the config first. I open the error log and reload the page. In nine cases out of ten the log line tells me the answer in plain words, and the fix takes two minutes. Guessing usually turns a two-minute fix into an hour of changes that later need undoing.

What 502 Bad Gateway means in nginx

RFC 9110 defines 502 as a response from a server acting as a gateway or proxy that received an invalid response from an inbound server. In nginx terms, the browser reached nginx successfully, but nginx failed when talking to the upstream: it could not connect, the connection was reset, or the reply could not be parsed. That is why restarting nginx alone rarely helps. The problem is almost always behind it.

Status What happened Look at
502 Bad Gateway Upstream refused, reset or sent an invalid reply Upstream service, socket path, permissions, buffers
504 Gateway Timeout Upstream accepted but did not reply in time Slow code or queries, proxy_read_timeout, fastcgi_read_timeout
500 Internal Server Error The app itself returned an error Application and PHP error logs
503 Service Unavailable Maintenance mode, rate limiting or no available upstream Maintenance files, limit_req, upstream health

Step 1: read the nginx error log

# Watch the error log while you reload the page
sudo tail -f /var/log/nginx/error.log

# Or search the last matches for 502 causes
sudo grep -E "upstream|connect()|recv()" /var/log/nginx/error.log | tail -n 20

If your site has its own error_log directive, check that file instead. Each 502 produces a line with the client, the request and the upstream. These are the messages you will meet most often:

connect() to unix:/run/php/php8.3-fpm.sock failed (2: No such file or directory) while connecting to upstream
connect() to unix:/run/php/php8.3-fpm.sock failed (13: Permission denied) while connecting to upstream
connect() failed (111: Connection refused) while connecting to upstream, upstream: "http://127.0.0.1:3000/"
upstream prematurely closed connection while reading response header from upstream
upstream sent too big header while reading response header from upstream
recv() failed (104: Connection reset by peer) while reading response header from upstream
Log message Likely cause Go to
(2: No such file or directory) on a .sock PHP-FPM stopped, or nginx points to the wrong socket path PHP-FPM socket
(13: Permission denied) on a .sock Socket owner or mode does not allow the nginx user Permissions
(111: Connection refused) Nothing listening on that host and port Upstream app
upstream prematurely closed connection The app or PHP worker crashed mid-request Upstream app
upstream sent too big header Response headers bigger than the buffer Buffers
(104: Connection reset by peer) Worker killed, often by limits or memory pressure Capacity

Fix 1: PHP-FPM socket missing or wrong

This is the classic WordPress and Laravel 502. Either PHP-FPM is not running, or nginx points to a socket that does not exist. It happens constantly after a PHP upgrade, because each version has its own service and socket, for example php8.1-fpm.sock and php8.3-fpm.sock.

# Is PHP-FPM running, and which version?
systemctl list-units --type=service | grep fpm
sudo systemctl status php8.3-fpm

# Which socket does the pool really listen on?
grep -E "^listen" /etc/php/8.3/fpm/pool.d/*.conf
ls -l /run/php/

# Which socket does nginx point to?
sudo grep -R "fastcgi_pass" /etc/nginx/sites-enabled/

Start the service if it is stopped (sudo systemctl enable --now php8.3-fpm), then make the nginx fastcgi_pass match the pool’s listen value exactly:

# nginx site config: must match the pool's listen value exactly
location ~ .php$ {
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/run/php/php8.3-fpm.sock;
}

# After editing, always test before reloading
sudo nginx -t && sudo systemctl reload nginx

If you are planning a PHP version change, my guide to upgrading the PHP version for WordPress on Ubuntu includes the socket switch as an explicit step so this 502 never appears.

From my own work: After every PHP upgrade I run one grep for fastcgi_pass across all enabled sites before reloading nginx. On servers with ten or more sites, there is always one forgotten vhost that still points at the old socket, and it is usually the client who notices first.

Fix 2: socket permission denied

Error 13 means the socket exists but the nginx worker user, usually www-data on Ubuntu and Debian or nginx on RHEL-based systems, cannot open it. Set the socket owner, group and mode in the pool file and restart PHP-FPM:

; /etc/php/8.3/fpm/pool.d/www.conf
listen = /run/php/php8.3-fpm.sock
listen.owner = www-data
listen.group = www-data
listen.mode = 0660

The options are documented in the PHP-FPM configuration manual. Panels such as CloudPanel run each site’s pool under its own user; in that case the listen owner is the site user and the group must still include the web server user. On RHEL, Rocky or Alma Linux, SELinux can also block sockets and ports; check sudo ausearch -m avc -ts recent before changing file modes.

Fix 3: the upstream app is down or crashed

For reverse proxies to Node.js, Python, Go or another server, error 111 means nothing is listening where nginx expects it. Check from the server itself:

# Is anything listening on the upstream port?
sudo ss -ltnp | grep -E ":3000|:8000|:8080"

# Does the app answer locally, without nginx?
curl -i http://127.0.0.1:3000/

# If the app runs under systemd, read its logs
sudo journalctl -u myapp -n 50 --no-pager

If curl fails too, the problem is the app, not nginx: it crashed, failed to start after a deploy, is listening on a different port, or only on a Unix socket. Fix the app and make it restart automatically under systemd or your process manager. If the app works with curl but nginx still returns 502, compare the address carefully, because localhost is a common trap:

# Fragile: "localhost" may resolve to ::1 (IPv6) while the app listens on 127.0.0.1 only
proxy_pass http://localhost:3000;

# Explicit and predictable
proxy_pass http://127.0.0.1:3000;

On many systems localhost resolves to both ::1 and 127.0.0.1. If the app listens on IPv4 only, attempts over IPv6 fail with connection refused. My guide to an nginx reverse proxy for Docker apps covers proxy headers and upstream blocks in more detail.

Fix 4: Docker and Docker Compose networking

Inside a container, 127.0.0.1 means the container itself. If nginx runs in one container and the app in another, use the Compose service name on the shared network, as described in the Docker Compose networking docs:

# Wrong inside a container: 127.0.0.1 is the nginx container itself
proxy_pass http://127.0.0.1:3000;

# Right with Docker Compose: use the service name on the shared network
proxy_pass http://app:3000;

If nginx runs on the host and the app in a container, publish the port to 127.0.0.1 only, for example 127.0.0.1:3000:3000, and proxy to that. Also remember that nginx resolves upstream hostnames at startup; if the app container was recreated with a new IP, reload nginx.

Fix 5: upstream sent too big header

Large cookies, long redirect URLs or many Set-Cookie headers can exceed the default buffer of one memory page. Increase the buffers in the relevant block, as documented for fastcgi and proxy modules:

# For PHP-FPM (inside the server or location block)
fastcgi_buffer_size 32k;
fastcgi_buffers 16 16k;

# For proxied apps
proxy_buffer_size 32k;
proxy_buffers 8 32k;

Raise them moderately, then look at why the headers are so large. A plugin writing huge cookies is a bug worth fixing at the source.

Fix 6: PHP-FPM or the app runs out of capacity

Intermittent 502s under traffic usually mean workers are exhausted or killed. Check the PHP-FPM log for the max children warning and the kernel log for the out-of-memory killer:

# Look for pool exhaustion in the PHP-FPM log
sudo grep -i "max_children" /var/log/php8.3-fpm.log | tail -n 5
# WARNING: [pool www] server reached pm.max_children setting (10), consider raising it

Run sudo dmesg -T | grep -i -E "killed process|out of memory" as well. Raising pm.max_children only helps if there is RAM for more workers; otherwise you trade 502s for swapping. My PHP-FPM tuning guide shows how to size the pool from real memory use per worker.

From my own work: The worst 502 I debugged recently came every night at the same minute. It was a backup job that pushed the VPS into the out-of-memory killer, which picked PHP-FPM workers. Moving the backup off-peak and adding a small swap file fixed it. The error log said connection reset; the kernel log said why.

502 behind Cloudflare or a load balancer

If the 502 page is branded by Cloudflare, Cloudflare could not get a valid response from your origin. Test the origin directly with curl -I --resolve example.com:443:YOUR_SERVER_IP https://example.com/ and check your nginx logs for that time. Cloudflare’s 502 and 504 troubleshooting page explains how to tell their errors from your origin’s. If there is no request in your access log at all, look at firewalls and origin certificate settings rather than PHP.

How to prevent the next 502

  1. Always run sudo nginx -t before systemctl reload nginx.
  2. Enable services at boot with systemctl enable for PHP-FPM and every app.
  3. Add restart policies such as Restart=on-failure in systemd units or restart: unless-stopped in Compose.
  4. Monitor from outside with an HTTP keyword check; my Uptime Kuma monitoring guide shows a setup that alerts within a minute.
  5. Keep logs readable with rotation so error logs never fill the disk.
  6. Write down socket paths and ports for each site, and update them as part of every upgrade checklist.

nginx 502 bad gateway checklist

  • Read the error log line for the failing request first.
  • No such file: start PHP-FPM or fix the socket path.
  • Permission denied: fix listen.owner, group and mode, or SELinux.
  • Connection refused: start the app and check the port and IPv4 vs IPv6.
  • Docker: use service names, not 127.0.0.1, between containers.
  • Too big header: raise buffers and fix oversized cookies.
  • Intermittent under load: check max_children and the OOM killer.
  • Cloudflare-branded 502: test the origin directly.
  • Test with nginx -t, then reload.

Want this done on your own server or site?

I am Saizul Amin, a web developer and technical SEO consultant. I set up and harden VPS servers, migrate WordPress sites, fix indexing problems and build automations. See my portfolio or get in touch.

FAQ

What does 502 Bad Gateway mean in nginx?

It means nginx, acting as a gateway or reverse proxy, received an invalid response from the upstream server or could not connect to it at all. The upstream is usually PHP-FPM, a Node.js, Python or Go app, or another server.

How do I find the cause of an nginx 502 error?

Read the nginx error log, usually /var/log/nginx/error.log, while reloading the failing page. The line for your request names the upstream and the reason, such as connection refused, a missing socket or a permission error.

What is the difference between 502 and 504 in nginx?

A 502 means the upstream refused the connection, closed it early or sent an invalid response. A 504 means nginx connected but the upstream did not answer within the timeout, such as proxy_read_timeout or fastcgi_read_timeout.

Why do I get 502 Bad Gateway after upgrading PHP?

The new PHP version uses a new PHP-FPM service and socket path, for example php8.3-fpm.sock instead of php8.1-fpm.sock, while nginx still points to the old socket. Update fastcgi_pass, test with nginx -t and reload.

Can Cloudflare cause a 502 error?

Cloudflare shows its own 502 page when it cannot get a valid response from your origin. If the page is branded by Cloudflare, check that your origin server is up and its nginx logs, then follow Cloudflare’s 5xx troubleshooting guide.

About the author. Saizul Amin is a web developer and technical SEO consultant from Dhaka who manages Ubuntu VPS servers, nginx, Cloudflare, WordPress and n8n in production for his own and client sites. Every command in these guides is one he runs himself; his open-source tools are on GitHub and his client work is at saizul.com.

Sources

NEW BLOGS. REAL STRATEGIES. REAL RESULTS.

Join our community and receive powerful SEO tips, web optimization guides, and growth strategies as soon as they’re published.

Don’t just read blogs — stay ahead of the competition.

We don’t spam! Read our privacy policy for more info.

Share.

Comments are closed.