Fixing a 502 Bad Gateway error
A 502 Bad Gateway means your web server failed to respond. Diagnose upstream server issues, PHP-FPM crashes, and timeout problems.
A 502 Bad Gateway error means the web server (Nginx/Apache) is working, but the upstream application server (PHP-FPM, Node.js, etc.) failed to respond or crashed. The web server cannot forward your request properly.
Common causes
- PHP-FPM crashed or stopped - The PHP processor is not running
- Resource limits exceeded - Memory or CPU exhausted, process killed
- Upstream timeout - Application took too long to respond
- Application error - PHP fatal error preventing startup
- Too many connections - All available processes are busy
- Database connection failure - Cannot connect to MySQL/database
How to diagnose
Check the error logs to see what caused the failure:
# For Nginx + PHP-FPM
tail -f /var/log/nginx/error.log
tail -f /var/log/php-fpm.log
# For Apache
tail -f /var/log/apache2/error.log
# Application-specific logs (WordPress)
tail -f /var/www/yourdomain.com/wp-content/debug.log
Common log messages:
connect() failed (111: Connection refused)- Application not listening on socketupstream timed out (110: Connection timed out)- Application too slowPHP Fatal error- PHP code crashed during startup
How to fix it
Step 1: Restart PHP-FPM
systemctl restart php-fpm
Step 2: Check PHP error logs
tail -50 /var/log/php-fpm.log | grep -i error
Step 3: Increase PHP-FPM worker processes
If traffic is high, increase available workers in /etc/php-fpm.d/www.conf:
pm.max_children = 50 # Increase from default 20
pm.start_servers = 10
pm.min_spare_servers = 5
pm.max_spare_servers = 15
Step 4: Increase timeout values
# In Nginx config
fastcgi_connect_timeout 30s;
fastcgi_send_timeout 30s;
fastcgi_read_timeout 30s;
Step 5: Check database connectivity
If using WordPress/MySQL, verify database credentials in wp-config.php are correct and MySQL is running:
systemctl status mysql
mysql -u user -p database_name -e "SELECT 1;"
Prevention tips
- Monitor PHP processes - Use htop to watch PHP-FPM worker usage
- Set appropriate limits - Allocate enough workers for your traffic
- Enable opcache - Speeds up PHP execution, reduces crashes
- Monitor resources - Keep RAM and CPU usage reasonable
- Regular backups - In case application files are corrupted
Related: Fixing a 503 Service Unavailable error | Fixing a 504 Gateway Timeout error | Error logs in cPanel
Still troubleshooting?
Use UnderHost tools for quick checks, or open a support ticket when the issue needs account or server access.





















