How to Fix Nginx 502 Bad Gateway on Ubuntu 22.04
-
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.sockinstead ofphp8.1-fpm.sock), or thephp8.1-fpmservice being down or unresponsive. -
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 -
Configuration Check Edit your Nginx server block configuration file. This is typically located in
/etc/nginx/sites-available/your_domain.confor a similar path. Verify that thefastcgi_passdirective within thelocation ~ \.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 -
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.serviceA successful fix will result in an HTTP 200 OK status from the
curlcommand and both services showing asactive (running).