Current Location: Home> Latest Articles> How to Fix php-fpm 502 Bad Gateway Errors: Causes and Solutions

How to Fix php-fpm 502 Bad Gateway Errors: Causes and Solutions

gitbox 2025-06-23

Background: Understanding the PHP-FPM 502 Error

PHP-FPM (FastCGI Process Manager) is a widely used PHP execution engine, especially in high-concurrency environments with Nginx. A 502 Bad Gateway error usually indicates that Nginx is unable to successfully communicate with PHP-FPM. This article explores common causes and practical fixes to help restore proper server functionality.

1. PHP-FPM Process Crashed

Under high traffic, PHP-FPM processes may become unstable and crash, resulting in 502 errors. You can check the process status and restart it if necessary:


$ systemctl status php-fpm
$ systemctl restart php-fpm

2. Improper PHP-FPM Pool Configuration

If the PHP-FPM pool parameters are not set correctly—such as having too few available workers—it can lead to request failures. Edit the pool configuration to adjust the following:


$ vim /etc/php-fpm.d/www.conf

Recommended settings:


pm.max_children = 50
pm.start_servers = 20
pm.min_spare_servers = 10
pm.max_spare_servers = 30
pm.max_requests = 500

3. Request Timeout Issues

Long-running scripts, such as those processing large files or complex logic, may exceed the default timeout, causing a 502 error. Increase the timeout setting as follows:


$ vim /etc/php-fpm.d/www.conf

Update this parameter:


request_terminate_timeout = 180

4. Nginx Misconfiguration

If Nginx is not properly configured to pass requests to PHP-FPM, a 502 error may occur. Check your nginx.conf file and ensure the following location block is correctly set:


$ vim /etc/nginx/nginx.conf

Example configuration:


location ~ \.php$ {
    include fastcgi_params;
    fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}

5. Insufficient Server Resources

If the server is running out of memory or CPU, PHP-FPM may be unable to spawn new processes, resulting in failed responses. Use these commands to monitor resource usage:


$ top
$ free -m

If resources are indeed constrained, consider upgrading the server or optimizing application performance to reduce load.

Conclusion

Resolving PHP-FPM 502 errors requires analyzing various aspects including process health, configuration tuning, timeout settings, proxy communication between Nginx and PHP-FPM, and system resources. By following these strategies, you can improve server reliability and minimize downtime.