nginx 502 Bad Gateway

Last Updated on

1.0 502 Bad Gateway

nginx 502 Bad Gateway

After the update of Linux on the web server, the website would not open in the browser. Instead the following error was displayed.

502 Bad Gateway
nginx/1.14.0

2.0 Solution

First we check the nginx server.

$ systemctl status nginx
● nginx.service - A high performance web server and a reverse proxy server
   Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
   Active: active (running) since Thu 2019-03-21 15:16:47 UTC; 16h ago
     Docs: man:nginx(8)
 Main PID: 1354 (nginx)
    Tasks: 8 (limit: 1158)
   CGroup: /system.slice/nginx.service
           ├─1354 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
           └─1355 nginx: worker process

Warning: Journal has been rotated since unit was started. Log output is incomplete or unavailable.

which seems to be OK. Next, we check the nginx configuration in the /etc/nginx/nginx.conf file. It says,

    ...
    location ~ \.php$ {
            include fastcgi_params;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            fastcgi_intercept_errors on;
            fastcgi_pass unix:/run/php/php7.2-fpm.sock;
    }
    ...

This says that the server uses a UNIX socket for proxying requests to the backend. The error "502 Bad Gateway" suggests that nginx has a difficulty in communicating with the backend and is not able to act as a "gateway" (proxy).

Next, we check the FastCGI Process Manager (fpm) service.

$ systemctl status php7.2-fpm.service
● php7.2-fpm.service - The PHP 7.2 FastCGI Process Manager
   Loaded: loaded (/lib/systemd/system/php7.2-fpm.service; enabled; vendor preset: enabled)
   Active: failed (Result: timeout) since Thu 2019-03-21 07:23:47 UTC; 1min 23s ago
     Docs: man:php-fpm7.2(8)
  Process: 1167 ExecStart=/usr/sbin/php-fpm7.2 --nodaemonize --fpm-config /etc/php/7.2/fpm/php-fpm.conf (code=killed, signal=TERM)
 Main PID: 1167 (code=killed, signal=TERM)

Warning: Journal has been rotated since unit was started. Log output is incomplete or unavailable.

Which says that the php7.2-fpm service has failed because of a timeout. This is corroborated by the syslog entry, which says,

Mar 20 17:37:45 exampleserver systemd[1]: php7.2-fpm.service: Start operation timed out. Terminating.
Mar 20 17:37:45 exampleserver systemd[1]: php7.2-fpm.service: Failed with result 'timeout'.
Mar 20 17:37:45 exampleserver systemd[1]: Failed to start The PHP 7.2 FastCGI Process Manager.

The solution is to add the following two lines in the /lib/systemd/system/php7.2-fpm.service unit file.

TimeoutStartSec=300s
TimeoutStopSec=300s

Finally, we start the php7.2-fpm service.

$ sudo systemctl daemon-reload
$ sudo systemctl start php7.2-fpm