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 (or php7.4-fpm, php8.1-fpm depending on version)

The 502 Bad Gateway error in Nginx indicates a problem specific to your Nginx configuration or environment. This guide provides platform-specific solutions.

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 (or php7.4-fpm, php8.1-fpm depending on version)
  2. If stopped, start it: sudo systemctl start php-fpm
  3. Enable at boot: sudo systemctl enable php-fpm
  4. Check PHP-FPM error logs: sudo tail -f /var/log/php-fpm/error.log
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/7.4/fpm/pool.d/www.conf 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/7.4/fpm/pool.d/www.conf
  2. Increase pm.max_children = 50
  3. Adjust pm.start_servers, pm.min_spare_servers, pm.max_spare_servers
  4. Restart PHP-FPM: sudo systemctl restart php-fpm

Prevention Tips