502 Bad Gateway: Causes and How to Fix It on Nginx
Getting 502 Bad Gateway? Read the Nginx error log, restart PHP-FPM or your app, fix the upstream port or socket, raise pm.max_children, check Cloudflare.

Contents
- Step one: read the Nginx error log
- The application or PHP-FPM is not running
- Wrong upstream port or socket path
- Socket permission denied
- PHP-FPM has run out of workers: pm.max_children
- The application is killed when memory runs out
- upstream sent too big header
- Timeouts: 502 or 504?
- SELinux on AlmaLinux
- Apache mod_proxy
- Cloudflare 502 errors
- Docker: container name, port and network
- Shared hosting
- Test and reload Nginx
- Quick checklist
- Fixing 502 errors at Nodesty
A 502 Bad Gateway error means that a server in front of your site, usually Nginx, a CDN or a load balancer, passed the request on to the application behind it and got no usable response back. The proxy is working; the problem is almost always the upstream: PHP-FPM, a Node.js or Python application, or a Docker container that is down, listening somewhere else or crashing under load.
This guide shows how to find the exact cause in the Nginx error log and fix the most common ones: a stopped service, a wrong port or socket, a full PHP-FPM pool, memory problems, oversized headers, SELinux, Cloudflare and Docker. For an overview of all status codes, see our HTTP error codes guide.
Step one: read the Nginx error log
The browser only shows "502 Bad Gateway", but Nginx writes the reason to its error log. After connecting to your server over SSH, look at the last lines:
sudo tail -n 50 /var/log/nginx/error.log
If a site has its own error_log line in its server block, check that file instead. Reload the page in the browser while running sudo tail -f /var/log/nginx/error.log to see the new line appear. These are the messages you will see most often:
| Message in error.log | What it usually means |
|---|---|
connect() failed (111: Connection refused) | Nothing listens on that port: the app is down |
connect() to unix:/run/php/php8.3-fpm.sock failed (2: ...) | The socket doesn't exist: wrong path or FPM stopped |
connect() to unix:... failed (13: Permission denied) | Nginx may not open the socket, or SELinux blocks it |
upstream prematurely closed connection | The app crashed or was killed while answering |
upstream sent too big header | Response headers larger than Nginx's buffer |
upstream timed out (110: Connection timed out) | The app is too slow; Nginx returns 504 for this one |
Each line also contains upstream: "...", the exact address Nginx tried to reach. Compare it with where your application really listens.
The application or PHP-FPM is not running
The most common cause by far. For PHP sites, check the PHP-FPM service (replace 8.3 with your version):
systemctl status php8.3-fpm
sudo systemctl restart php8.3-fpm
On AlmaLinux the service is simply called php-fpm. For a Node.js or Python application, check the process manager you use:
pm2 status
pm2 logs --lines 50
sudo systemctl status myapp
sudo journalctl -u myapp -n 50
If the service won't start, its own log shows why: a syntax error, a missing environment variable or a port that's already taken (see Port already in use). To make sure the app comes back after a crash or reboot, run it as a service as described in How to create a systemd service. For a Python app behind Gunicorn, our How to deploy a Python app guide shows a working setup.
Wrong upstream port or socket path
If the application runs but Nginx still gets Connection refused, Nginx is knocking on the wrong door. Compare the address in proxy_pass or fastcgi_pass with what is actually listening:
sudo ss -tlnp | grep -E 'node|python|php|gunicorn'
ls -l /run/php/
A classic case is a PHP upgrade: the new version creates /run/php/php8.4-fpm.sock, but the site still points to php8.3-fpm.sock, which no longer exists, so the log shows (2: No such file or directory). Update the fastcgi_pass line to the new socket, as shown in How to change the PHP version.
Another quiet trap is localhost. If proxy_pass http://localhost:3000; resolves to the IPv6 address ::1 but the app only listens on 127.0.0.1, the connection is refused. Write the address explicitly:
location / {
proxy_pass http://127.0.0.1:3000;
}
Socket permission denied
(13: Permission denied) on a PHP-FPM socket means the Nginx user can't open it. On Ubuntu and Debian, Nginx runs as www-data, and the pool file /etc/php/8.3/fpm/pool.d/www.conf should match:
listen = /run/php/php8.3-fpm.sock
listen.owner = www-data
listen.group = www-data
listen.mode = 0660
On AlmaLinux, Nginx runs as nginx, and the default pool listens on /run/php-fpm/www.sock; make sure nginx is in listen.acl_users in /etc/php-fpm.d/www.conf. Restart PHP-FPM after any change.
PHP-FPM has run out of workers: pm.max_children
If 502 errors only appear under load, look at the PHP-FPM log:
sudo grep max_children /var/log/php8.3-fpm.log
A line like WARNING: [pool www] server reached pm.max_children setting (5), consider raising it means every PHP worker was busy. The Debian and Ubuntu default of 5 is low for a busy site. Find out how much memory one worker uses on average:
ps --no-headers -o rss -C php-fpm8.3 | awk '{s+=$1} END {print s/NR/1024 " MB"}'
Divide the RAM you can give to PHP by that number. With 4 GB left for PHP and workers of about 80 MB, around 50 is a reasonable limit. Set it in the pool file and restart PHP-FPM:
pm = dynamic
pm.max_children = 50
pm.start_servers = 10
pm.min_spare_servers = 5
pm.max_spare_servers = 15
Don't set the value higher than your RAM allows: too many workers push the server into swap or out of memory, which leads straight to the next cause.
The application is killed when memory runs out
When the server runs out of RAM, the kernel's OOM killer ends the process using the most memory, often PHP-FPM workers, Node.js or the database. Nginx then sees a closed connection or a refused port. Check whether this happened:
sudo dmesg -T | grep -i -E 'out of memory|killed process'
free -h
If you find matches, reduce memory usage (fewer workers, lower limits), add swap as a buffer as explained in How to add swap on Linux, or move to a plan with more RAM. Our Why is my server slow? guide helps you find what's eating the resources.
upstream sent too big header
Applications that set large cookies or many headers (some WordPress plugins, authentication proxies) can exceed Nginx's default buffer. Raise it in the location block, depending on whether you use proxy_pass or PHP-FPM:
# Reverse proxy (proxy_pass)
proxy_buffer_size 16k;
proxy_buffers 8 16k;
# PHP-FPM (fastcgi_pass)
fastcgi_buffer_size 32k;
fastcgi_buffers 16 16k;
Timeouts: 502 or 504?
If the application is too slow, Nginx returns 504 Gateway Timeout after proxy_read_timeout (60 seconds by default). For long tasks such as exports, you can raise it for a single location with proxy_read_timeout 300s; (or fastcgi_read_timeout for PHP). A slow request can still end in a 502, though: if PHP's max_execution_time or the pool's request_terminate_timeout kills the worker first, Nginx logs upstream prematurely closed connection. Fixing the slow code or query is the real cure; longer timeouts only hide it.
SELinux on AlmaLinux
On AlmaLinux and other RHEL-based systems, SELinux doesn't allow Nginx to open network connections to an application by default. The log shows connect() to 127.0.0.1:3000 failed (13: Permission denied) even though the app runs. Allow it permanently:
sudo setsebool -P httpd_can_network_connect 1
Don't disable SELinux entirely to fix this; the single boolean is enough.
Apache mod_proxy
If Apache is your reverse proxy, the log is /var/log/apache2/error.log (on AlmaLinux /var/log/httpd/error_log). A message like AH01102: error reading status line from remote server means the backend answered with something invalid or closed the connection. Note that Apache usually reports a backend that refuses connections as 503 rather than 502. The checks are the same: is the backend running, and do the ProxyPass address and port match?
Cloudflare 502 errors
If your site is behind Cloudflare, first look at the error page. A Cloudflare-branded 502 or 504 page points to a problem in Cloudflare's network, so check their status page. A plain page with nginx at the bottom came from your origin server, and all the steps above apply. Cloudflare's own codes are more specific: 521 means your web server refused the connection, and 522 means the connection timed out, often because a firewall blocks Cloudflare's IP ranges.
To test the origin without Cloudflare, send the request directly to the server's IP:
curl -I --resolve yourdomain.com:443:203.0.113.10 https://yourdomain.com
Docker: container name, port and network
When Nginx runs in a container, 127.0.0.1 means the Nginx container itself, not your app. Put both on the same Docker network and use the service name and the port the app listens on inside its container:
proxy_pass http://app:3000;
The app must listen on 0.0.0.0 inside its container, not only on 127.0.0.1. Check that the container is running with docker ps and docker logs app. Nginx resolves the name at startup, so after the app container is recreated with a new IP, reload Nginx too. If Nginx runs on the host, publish the port (for example -p 127.0.0.1:3000:3000) and proxy to 127.0.0.1:3000. Docker basics are in How to install Docker.
Shared hosting
On shared hosting you don't control the proxy or PHP-FPM, so a 502 usually comes from your account hitting its resource limits (CPU, memory or entry processes) or from a problem on the provider's side. Check the Resource Usage page in cPanel and the error log, disable recently added plugins and, if the error persists, contact support with the exact time it appeared.
Test and reload Nginx
After every configuration change, test before reloading so that a typo doesn't take all your sites down:
sudo nginx -t
sudo systemctl reload nginx
Quick checklist
| Check | Command or place |
|---|---|
| What does Nginx say? | sudo tail -n 50 /var/log/nginx/error.log |
| Is the backend running? | systemctl status php8.3-fpm, pm2 status |
| Does the address match? | ss -tlnp, ls /run/php/ vs proxy_pass |
| Is the FPM pool full? | max_children in /var/log/php8.3-fpm.log |
| Was something killed? | Killed process in dmesg -T |
| AlmaLinux only | setsebool -P httpd_can_network_connect 1 |
| Behind Cloudflare? | Branded page or origin page, curl --resolve |
| Config valid? | nginx -t, then systemctl reload nginx |
New to Nginx configuration? Our How to install Nginx guide covers server blocks and reverse proxy setup from the start.
Fixing 502 errors at Nodesty
On Nodesty AMD Ryzen 9 9950X VPS plans you have full root access, so you can read every log, tune PHP-FPM and Nginx and restart services yourself, on NVMe storage with free daily backups kept for 7 days. If you'd rather not manage a server, Nodesty web hosting runs your sites on AMD Ryzen 9 7900 servers with the LiteSpeed web server, NVMe storage and cPanel or DirectAdmin, where you can see resource usage and error logs from the panel.
Frequently Asked Questions
What does 502 Bad Gateway mean?
A server acting as a gateway or proxy, usually Nginx, a CDN like Cloudflare or a load balancer, tried to pass your request to the server behind it and got no valid response. The proxy itself works; the application, PHP-FPM or container behind it is down, unreachable or answered with something the proxy couldn't use.
Is a 502 error my fault as a visitor?
No. A 502 is a server-side error, and clearing the cache or changing the browser rarely helps. As a visitor you can only wait a few minutes and try again. If you own the site, the web server's error log tells you why the proxy couldn't reach the application.
What is the difference between 502 and 504?
With a 502, the proxy got no valid answer at all, for example because the connection was refused or the application crashed mid-request. With a 504, the application accepted the connection but didn't answer within the proxy's timeout. A 502 usually points to something that is down or misconfigured, a 504 to something that is too slow.
Why does the 502 error come and go?
Intermittent 502 errors usually mean the backend runs out of capacity under load. PHP-FPM reaches its pm.max_children limit, the application is killed when memory runs out and restarts, or a container restarts in a loop. Check the PHP-FPM log and dmesg for out of memory messages at the times the error appeared.
Does a 502 error hurt SEO?
A short outage doesn't. Search engines treat 5xx errors as temporary and try again later. If a site returns 502 for days, however, crawling slows down and pages may eventually drop out of the index, so recurring 502 errors should be fixed at the cause rather than with restarts.
I get 502 on shared hosting. What can I do?
On shared hosting you don't manage the web server or PHP-FPM yourself, so the cause is usually a resource limit of your account or a problem on the provider's side. Check the resource usage page in your control panel, look at the error log, disable a recently added plugin and contact support with the time of the error.
About the author
Nodesty Team · Infrastructure & Support
The Nodesty team runs our servers, network and DDoS protection day to day and answers customer support requests around the clock. These guides come from that work.
Related articles

WordPress Upload Size Limit: How to Increase It
Fix The uploaded file exceeds the upload_max_filesize directive in php.ini: raise the WordPress upload limit in cPanel, DirectAdmin, .user.ini or on a VPS.

How to Reset the WordPress Admin Password When Locked Out
Locked out of WordPress? Reset the admin password with the lost password link, WP-CLI, phpMyAdmin or MySQL, or create a new admin user from the terminal.

There Has Been a Critical Error on This Website: How to Fix It
WordPress says There has been a critical error on this website? Find the PHP error with WP_DEBUG, disable plugins or the theme and fix memory limits.