Error 502 Gateway

How to fix the Error 502 Bad Gateway on Nginx web server.

Usually, the Error 502 Bad Gateway shows when the Nginx web server cannot connect to backend services such as PHP-FPM.

The Error 502 Bad Gateway may appear under different error messages:

  • HTTP Error 502 - Bad Gateway
  • 502 Bad Gateway NGINX
  • 502 Bad Gateway
  • 502 Proxy Error
  • Temporary Error (502)
  • Error 502
  • HTTP 502

Fix Error 502 Bad Gateway

In order to fix the Error 502 Bad Gateway, there are a couple of solutions you can follow.

Check that your DNS records are set correctly

The DNS records of your website must be set correctly.

Temporarily disable CDN

If you use any CDN providers, such as CloudFlare, disable the provider to troubleshoot if the issue is from the CDN provider.

Check that the hard disk is not full

A full hard disk may cause the Error 502 Bad Gateway error.

If you use PHP-FPM

Check that the backend service (i.e. PHP-FM) works

Check that your backend service, such as PHP-FPM, runs correctly and it does not throw any errors:

sudo ps aux | grep 'php'

If PHP-FPM does not run, enable it and start it:

sudo systemctl enable php-fpm.service
sudo service php-fpm start

php-fpm.service may be named differently, such as `php7.2-fpm.service, depending on your PHP version.

If the PHP-FPM service runs, you can try to increase buffers and timeouts:

server {
    location / {
        fastcgi_buffers 8 16k;
        fastcgi_buffer_size 32k;
        fastcgi_connect_timeout 90;
        fastcgi_send_timeout 300;
        fastcgi_read_timeout 300;
    }
}

Reload the configuration file to test it:

sudo nginx -t

Restart Nginx:

sudo systemctl restart nginx

Check Nginx/PHP-FPM socket configuration

Check that your nginx.conf configuration file points to the correct socket file:

server {
    location / {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php-fpm.sock;
    }
}

The directory /var/run should contain the php-fpm.sock file. To check, run this command:

ls -l /var/run

If the output of the ls command doesn't show the php-fpm.sock file, the socket file was not created by PHP-FPM. If that's the case, check the chapter above.