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
- PHP-FPM service is not running or has crashed
- Nginx cannot connect to the FastCGI backend
- Firewall blocking connection between Nginx and PHP-FPM
- Incorrect fastcgi_pass directive in Nginx configuration
- PHP-FPM pool is full or has reached max_children limit
- Socket file permissions incorrect
Step-by-Step Solutions
Solution 1: Check if PHP-FPM is Running
- Check PHP-FPM status: sudo systemctl status php-fpm (or php7.4-fpm, php8.1-fpm depending on version)
- If stopped, start it: sudo systemctl start php-fpm
- Enable at boot: sudo systemctl enable php-fpm
- Check PHP-FPM error logs: sudo tail -f /var/log/php-fpm/error.log
Solution 2: Verify Nginx Configuration
- Check fastcgi_pass directive in /etc/nginx/sites-available/your-site
- For Unix socket: fastcgi_pass unix:/var/run/php/php-fpm.sock;
- For TCP: fastcgi_pass 127.0.0.1:9000;
- Test configuration: sudo nginx -t
- Reload Nginx: sudo systemctl reload nginx
Solution 3: Check Socket Permissions
- If using Unix socket, check permissions: ls -la /var/run/php/php-fpm.sock
- Should be owned by www-data:www-data or nginx:nginx
- In /etc/php/7.4/fpm/pool.d/www.conf set: listen.owner = www-data, listen.group = www-data, listen.mode = 0660
- Restart PHP-FPM: sudo systemctl restart php-fpm
Solution 4: Increase PHP-FPM Resources
- Edit /etc/php/7.4/fpm/pool.d/www.conf
- Increase pm.max_children = 50
- Adjust pm.start_servers, pm.min_spare_servers, pm.max_spare_servers
- Restart PHP-FPM: sudo systemctl restart php-fpm
Prevention Tips
- Monitor Nginx error logs regularly
- Implement proper health checks and monitoring
- Keep Nginx and dependencies up to date
- Set up alerting for error rate increases
- Document your configuration changes
- Test configuration changes in staging first