How to Fix Apache 502 Bad Gateway on Ubuntu 22.04


  1. 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.

  2. Quick Fix (CLI)

    sudo systemctl restart php8.1-fpm
    sudo systemctl restart apache2
  3. 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 (adjust 8.1 for your PHP version) Ensure the listen directive points to a valid Unix socket that Apache can access, and adjust request_terminate_timeout if scripts are taking too long.

    ; Example lines to check/change
    listen = /run/php/php8.1-fpm.sock
    request_terminate_timeout = 300s

    Apache Virtual Host Configuration: File: /etc/apache2/sites-available/your-site.conf (or /etc/apache2/apache2.conf for global settings) Verify that the ProxyPassMatch or SetHandler directive correctly points to the PHP-FPM Unix socket and that ProxyTimeout is sufficient. Ensure mod_proxy and mod_proxy_fcgi are 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>
  4. Verification

    sudo systemctl status php8.1-fpm && sudo systemctl status apache2 && curl -I http://localhost/