HTTPError.net

The fastest way to diagnose, understand, and fix any HTTP status code

Nginx

How to Fix 502 Bad Gateway Error in Nginx

Quick Fix

The most common cause of 502 errors in Nginx is: PHP-FPM service is not running or has crashed

Quick solution: Check PHP-FPM status: sudo systemctl status php-fpm (on Debian/Ubuntu the service is versioned, e.g. php8.2-fpm)

A 502 Bad Gateway error in Nginx is usually caused by one of a handful of configuration problems. Work through the causes below in order - the first ones are the most common.

Common Causes in Nginx

Step-by-Step Solutions

Solution 1: Check if PHP-FPM is Running
  1. Check PHP-FPM status: sudo systemctl status php-fpm (on Debian/Ubuntu the service is versioned, e.g. php8.2-fpm)
  2. If stopped, start it: sudo systemctl start php-fpm
  3. Enable at boot: sudo systemctl enable php-fpm
  4. Check PHP-FPM logs: sudo journalctl -u php8.2-fpm (or /var/log/php-fpm/error.log on RHEL)
Solution 2: Verify Nginx Configuration
  1. Check fastcgi_pass directive in /etc/nginx/sites-available/your-site
  2. For Unix socket: fastcgi_pass unix:/var/run/php/php-fpm.sock;
  3. For TCP: fastcgi_pass 127.0.0.1:9000;
  4. Test configuration: sudo nginx -t
  5. Reload Nginx: sudo systemctl reload nginx
Solution 3: Check Socket Permissions
  1. If using Unix socket, check permissions: ls -la /var/run/php/php-fpm.sock
  2. Should be owned by www-data:www-data or nginx:nginx
  3. In /etc/php/8.2/fpm/pool.d/www.conf (adjust the version) set: listen.owner = www-data, listen.group = www-data, listen.mode = 0660
  4. Restart PHP-FPM: sudo systemctl restart php-fpm
Solution 4: Increase PHP-FPM Resources
  1. Edit /etc/php/8.2/fpm/pool.d/www.conf (adjust the version)
  2. Raise pm.max_children (size it to available RAM divided by the memory used per PHP process)
  3. Adjust pm.start_servers, pm.min_spare_servers, pm.max_spare_servers
  4. Restart PHP-FPM: sudo systemctl restart php-fpm

Prevention Tips