How to Fix Nginx 502 Bad Gateway on Ubuntu 22.04


  1. The Root Cause On Ubuntu 22.04, an Nginx 502 Bad Gateway error commonly indicates that Nginx cannot connect to the PHP-FPM service. This typically stems from Nginx being configured to point to an incorrect or non-existent PHP-FPM Unix socket (e.g., php-fpm.sock instead of php8.1-fpm.sock), or the php8.1-fpm service being down or unresponsive.

  2. Quick Fix (CLI)

    # Check current status of PHP-FPM and Nginx
    sudo systemctl status php8.1-fpm.service
    sudo systemctl status nginx.service
    
    # Restart PHP-FPM and Nginx services to re-establish connection
    sudo systemctl restart php8.1-fpm.service
    sudo systemctl restart nginx.service
  3. Configuration Check Edit your Nginx server block configuration file. This is typically located in /etc/nginx/sites-available/your_domain.conf or a similar path. Verify that the fastcgi_pass directive within the location ~ \.php$ block correctly points to the PHP 8.1 FPM Unix socket path.

    # Example: /etc/nginx/sites-available/your_domain.conf
    
    server {
        listen 80;
        server_name your_domain.com;
        root /var/www/your_domain;
        index index.php index.html;
    
        location / {
            try_files $uri $uri/ =404;
        }
    
        location ~ \.php$ {
            include snippets/fastcgi-php.conf;
            # CRITICAL: Ensure this line specifies the correct PHP-FPM socket
            fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
            fastcgi_split_path_info ^(.+\.php)(/.+)$;
            fastcgi_index index.php;
        }
    
        # ... other configurations ...
    }

    After making changes, test the Nginx configuration syntax and reload Nginx:

    sudo nginx -t
    sudo systemctl reload nginx.service
  4. Verification

    # Check the HTTP status code for your domain or localhost
    curl -I http://localhost
    
    # If you have a phpinfo.php file, test it directly
    # curl http://localhost/phpinfo.php
    
    # Confirm both services are running without errors
    sudo systemctl status php8.1-fpm.service
    sudo systemctl status nginx.service

    A successful fix will result in an HTTP 200 OK status from the curl command and both services showing as active (running).