How to Fix Apache 502 Bad Gateway on Ubuntu 22.04
-
The Root Cause On Ubuntu 22.04, an Apache 502 Bad Gateway error commonly indicates that Apache, acting as a reverse proxy (usually via
mod_proxy_fcgi), cannot successfully communicate with the backend PHP-FPM service. This typically occurs when PHP-FPM is not running, is overloaded, or its Unix socket path configured in Apache does not match the one PHP-FPM is listening on, preventing Apache from receiving a valid response. -
Quick Fix (CLI)
sudo systemctl restart php8.1-fpm sudo systemctl restart apache2 -
Configuration Check
Edit the PHP-FPM pool configuration file and the Apache virtual host configuration.
PHP-FPM Pool Configuration: File:
/etc/php/8.1/fpm/pool.d/www.conf(adjust8.1for your PHP version) Ensure thelistendirective points to a valid Unix socket that Apache can access, and adjustrequest_terminate_timeoutif scripts are taking too long.; Example lines to check/change listen = /run/php/php8.1-fpm.sock request_terminate_timeout = 300sApache Virtual Host Configuration: File:
/etc/apache2/sites-available/your-site.conf(or/etc/apache2/apache2.conffor global settings) Verify that theProxyPassMatchorSetHandlerdirective correctly points to the PHP-FPM Unix socket and thatProxyTimeoutis sufficient. Ensuremod_proxyandmod_proxy_fcgiare enabled (sudo a2enmod proxy proxy_fcgi).# Example lines to check/change in your virtual host <VirtualHost *:80> ServerName yourdomain.com DocumentRoot /var/www/html # Ensure mod_proxy_fcgi is enabled and configured correctly <IfModule mod_proxy_fcgi.c> <FilesMatch \.php$> # Use the same socket path as defined in php-fpm's www.conf SetHandler "proxy:unix:/run/php/php8.1-fpm.sock|fcgi://localhost/" </FilesMatch> </IfModule> # Increase timeout if scripts are long-running ProxyTimeout 300 Timeout 300 ErrorLog ${APACHE_LOG_DIR}/yourdomain-error.log CustomLog ${APACHE_LOG_DIR}/yourdomain-access.log combined </VirtualHost> -
Verification
sudo systemctl status php8.1-fpm && sudo systemctl status apache2 && curl -I http://localhost/