PromptHub
DevOps Error 502 Intermediate 16 views

Nginx 502 Bad Gateway

Nginx received an invalid response from the upstream server (PHP-FPM, Node.js, etc.).

Explanation

Nginx 502 Bad Gateway means Nginx received an invalid, incomplete, or no response from the upstream server it's proxying to. This is common when the PHP-FPM process crashes or isn't running, when the Node.js application crashes, when there's a timeout connecting to the backend, or when the backend returns malformed headers. The error can also occur during high traffic when the backend is overwhelmed. Nginx itself is working fine, but the service it's forwarding requests to is not.

Common Causes

  • PHP-FPM process not running
  • Backend application crashed
  • Socket/port mismatch in config
  • Backend overwhelmed with requests
  • File permission issues

Solution

Check if the upstream service (PHP-FPM, Node.js) is running: systemctl status php-fpm or pm2 list. Check Nginx error logs: tail -f /var/log/nginx/error.log. Verify the upstream server configuration in Nginx (fastcgi_pass, proxy_pass). Ensure the socket or port in Nginx config matches what the backend is listening on. Restart the backend service: systemctl restart php-fpm. Check for PHP fatal errors that crash the FPM worker. Increase PHP-FPM timeout settings if needed. Verify file permissions allow the backend to read application files.

Code Example

# Nginx upstream configuration
# /etc/nginx/sites-available/myapp
server {
    listen 80;
    server_name example.com;
    root /var/www/myapp/public;

    location / {
        try_files \$uri \$uri/ /index.php\$query_string;
    }

    location ~ \.php\$ {
        fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
        fastcgi_param SCRIPT_FILENAME \$realpath_root\$fastcgi_script_name;
        include fastcgi_params;
    }
}

# Fix: ensure PHP-FPM is running
sudo systemctl status php8.2-fpm
sudo systemctl start php8.2-fpm

# Check Nginx error log
sudo tail -f /var/log/nginx/error.log

# Common causes in logs:
# connect() failed (111: Connection refused) -> PHP-FPM not running
# upstream prematurely closed connection -> PHP crashed
# no live upstreams -> all backend workers down

# Restart services
sudo systemctl restart php8.2-fpm
sudo systemctl reload nginx

Error Information

Language

bash

Framework

nginx

Difficulty

Intermediate

Views

16

Related Errors