How to Fix Apache 502 Bad Gateway on Debian 11
-
The Root Cause Apache 502 Bad Gateway on Debian 11, when Apache acts as a reverse proxy (e.g., for PHP-FPM applications), primarily indicates a failure to establish communication or receive a timely response from the upstream application server. This often occurs because the backend process, such as
php-fpm, is stopped, overwhelmed, or has timed out, preventing Apache from successfully handing off the request. -
Quick Fix (CLI)
# Check the status of your PHP-FPM service (replace X.Y with your PHP version, e.g., 8.1) sudo systemctl status phpX.Y-fpm # If the service is inactive, failed, or unhealthy, restart it sudo systemctl restart phpX.Y-fpm # Restart Apache to ensure proxy connections are reset and any configuration changes are loaded sudo systemctl restart apache2 -
Configuration Check
-
Apache Virtual Host Configuration: File:
/etc/apache2/sites-available/your-site.conf(or the relevant virtual host file)Verify that
mod_proxy_fcgiis enabled (sudo a2enmod proxy_fcgiif not) and yourProxyPassMatchorSetHandlerdirective correctly points to the PHP-FPM Unix socket or TCP port. EnsureProxyTimeoutis set high enough for slow backend processes.# Ensure mod_proxy_fcgi is enabled. # This example uses SetHandler for PHP-FPM via Unix socket. <FilesMatch \.php$> SetHandler "proxy:unix:/run/php/phpX.Y-fpm.sock|fcgi://localhost/" </FilesMatch> # If using ProxyPassMatch, ensure the path is correct. # ProxyPassMatch ^/(.*\.php(/.*)?)$ unix:/run/php/phpX.Y-fpm.sock|fcgi://localhost/var/www/your-site/ # Increase the proxy timeout if backend scripts are complex or slow ProxyTimeout 300 -
PHP-FPM Pool Configuration: File:
/etc/php/X.Y/fpm/pool.d/www.conf(replaceX.Ywith your PHP version)Confirm that the
listendirective matches the socket path or TCP port configured in your Apache virtual host file. Additionally, reviewrequest_terminate_timeoutand resource limits (pm.max_children,memory_limit) to prevent FPM processes from being prematurely killed or running out of resources.; Ensure the listen directive matches Apache's proxy target listen = /run/php/phpX.Y-fpm.sock ; Increase request_terminate_timeout if scripts are timing out on the FPM side request_terminate_timeout = 300s ; Adjust PHP memory limit as needed php_admin_value[memory_limit] = 256M
-
-
Verification
# Verify the PHP-FPM service is active and running correctly sudo systemctl status phpX.Y-fpm # Verify the Apache2 service is active and running sudo systemctl status apache2 # Make an HTTP request to your application to confirm the issue is resolved curl -I http://your-domain.com/