How to Fix Apache 502 Bad Gateway on Debian 11


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

  2. 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
  3. Configuration Check

    • Apache Virtual Host Configuration: File: /etc/apache2/sites-available/your-site.conf (or the relevant virtual host file)

      Verify that mod_proxy_fcgi is enabled (sudo a2enmod proxy_fcgi if not) and your ProxyPassMatch or SetHandler directive correctly points to the PHP-FPM Unix socket or TCP port. Ensure ProxyTimeout is 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 (replace X.Y with your PHP version)

      Confirm that the listen directive matches the socket path or TCP port configured in your Apache virtual host file. Additionally, review request_terminate_timeout and 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
  4. 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/