Register Login

Fix 502 Bad Gateway Error

08 Oct 2020 12:46 pm || 0

So, you are at your work desk ready to work hard and conquer the day. But wait! As you open the website needed for your tasks, this happens –

 502 Bad Gateway Error

Frustrating isn’t it? You don’t understand what has happened or why! But you know you have to get it fixed as soon as possible.

Let us take a closer look at this issue.

What is 502 Bad Gateway Error?

To put it simply, a 502 Bad Gateway error indicates that there is something very wrong in the server communication of the website you are trying to access. When this happens, the error web page is displayed to the visitors, as shown earlier in the picture above.

In technical terms, a 502 Bad Gateway error means that the edge server (acting as proxy or gateway server) has received an invalid response from the origin server (upstream server). In the followings sections, we will discuss why this error usually pops up.

Different forms of the 502 Bad Gateway Error

Due to the technical differences of the browsers, operating systems and web servers, the 502 Bad Gateway error can project itself in different ways. But fortunately (or unfortunately), they mean the same thing.

Below is a list that tells you about the most common variations of this irritating issue –

  • “502 Bad Gateway”
  • “Error 502”
  • A blank white screen
  • “502 Server Error: The server encountered a temporary error and could not complete your request”
  • “HTTP 502”
  • “HTTP Error 502 – Bad Gateway”
  • “502 Proxy Error”
  • “502 Service Temporarily Overloaded”
  • 502 bad gateway Cloudflare
  • That’s an error
  • Bad Gateway: The proxy server received an invalid response from an upstream server
  • Temporary Error (502)

Why does NGINX return the 502 Bad Gateway error?

The PHP-FastCGI Process Manager (PHP-FPM) is used for working on server requests in PHP apps. This is usually run behind an NGINX web server. The server throws a 502 Bad Gateway error if PHP-FPM does not respond to its server request, or NGINX is not able to proxy a request properly.

Let us check out some other causes why this may happen –

  • PHP-FPM is not running
  • NGINX is not able to communicate with PHP-FPM
  • PHP-FPM timeout

PHP-FPM is not running

NGINX might throw the 502 error if a request sent to the PHP application does not reach it. This happens when the PHP-FPM is not running. In that case, you need to check whether the PHP-FPM is running properly. If you are on a LINUX host, use the pscommand to verify whether the PHP-FPM processes that are currently running, like this –

To fix this situation, you have to perform the following steps –

  • At first, check the error logs
  • Then, run the command given below on a LINUX terminal
tail -f /var/log/nginx/error.log
  • The output of the command will be something like this –
2020/09/21 19:58:56 [crit] 789#0: *65 connect() to unix:/opt/bitnami/php/var/run/www.sock failed (2: No such file or directory) while connecting to upstream, client: 66.249.65.231, server: localhost, request: "GET /u/sai-sravan-n/5e8151e57737d4593f62f949/ HTTP/1.1", upstream: "fastcgi://unix:/opt/bitnami/php/var/run/www.sock:", host: "localhost"

In the code written above, you can see the line

“65 connect() to unix:/opt/bitnami/php/var/run/www.sock failed”

This line explains that the NGINX server was not able to connect to the PHP-FPM server.

To fix this, just restart the PHP-FPM service by running the command below –

sudo service php-fpm start

If you are developing an application, you must use the systemd to execute the PHP-FPM as a service. The systemd is a useful suite of system components for LINUX systems. Using this will make your PHP application much more scalable and reliable. This is because the PHP-FPM daemon will communicate with the app when you start the server, or if a new instance is launched.

While setting up or configuring PHP, you can add the PHP-FPM as a systemd service. After it is configured as a service, use the command given below to make sure that it initiates when you start the server.

sudo systemctl enable php7.2-fpm.service

To check the status of the PHP-FPM service, run this command –

sudo service php-fpm status

Output

Unit php-fpm.service could not be found.

Or

sudo systemctl is-active php-fpm.service

Output:

Inactive

This indicates that the PHP-FPM service not running. Thus, you need to start the php-fpm service. Use the command below –

sudo service php-fpm start

This will fix the error.  

NGINX is Not Able to Communicate with PHP-FPM

After PHP-FPM is initiated, TCP or UNIX sockets are created to interact with the NGINX server. But if you are encountering a 502 error, it might be due to incorrect NGINX & PHP-FPM configuration settings. Both of them must be configured to make use of the same socket.

In this situation, you can check the error logs using the command given below –

tail -f /var/log/nginx/error.log
2020/09/21 19:58:56 [crit] 789#0: *65 connect() to unix:/opt/bitnami/php/var/run/www.sock failed (2: No such file or directory) while connecting to upstream, client: 66.249.65.231, server: localhost, request: "GET /u/sai-sravan-n/5e8151e57737d4593f62f949/ HTTP/1.1", upstream: "fastcgi://unix:/opt/bitnami/php/var/run/www.sock:", host: "localhost"

2: No such file or directory

This line indicates that the configuration settings are not correct.

PHP-FPM Configuration

PHP-FPM is often configured and optimized when you are planning to scale beyond a single system. Developers usually configure PHP-FPM for maximum performance and so that they can cut down on their server bills too!

PHP configuration file

sudo nano /etc/php-fpm.d/www.conf
Check the given parameters –
user = nginx
group = nginx
listen.owner = nginx
listen.group = nginx
;listen.acl_users = apache,nginx

You have to remember that these permissions must allow the user and group running the NGINX server accessibility to the socket. If you mess up the permissions while configuring the file, NGINX will throw a 502 error. This error will be logged into the access log and a message will be shown, like this –    

To determine whether a 502 error was caused by a socket misconfiguration, confirm that PHP-FPM and NGINX are configured to use the same socket.

sudo nano /etc/php-fpm.d/www.conf

Look for this line of code –

listen = /run/php/mypool.sock

Inside the nginx.conf file, make sure that the location block specifies the same socket. You can see in the code given below, that the include directive loads some of the basic information for PHP-FPM. The fastcgi_pass directive mentions the UNIX socket present in the main configuration file.      

index index.html index.htm index.php;
location ~ \.php$ {
    fastcgi_read_timeout 300;
    fastcgi_pass   unix:/run/php/mypool.sock;
    fastcgi_index  index.php;
    fastcgi_param  SCRIPT_FILENAME $request_filename;
    include        fastcgi_params;

}

In the above code, we need to check whether the “fastcgi_pass” and listen variable are the same.

PHP-FPM timeout

Users often experience a PHP-FPM timeout error if their application is taking too much time to respond. In the pool configuration’s request_terminate_timeout directive, the default timeout limit is 20 seconds. The timeout for NGINX is 60 seconds. The timeout error is shown when the PHP-FPM timeout is less than the NGINX timeout.

This is the error log you will see when the timeout occurs –

tail -f /var/log/nginx/error.log 

Output:

2020/09/19 14:46:38 [error] 6697#0: *1 upstream sent too big header while reading response header from upstream, client: 223.190.54.130, server: localhost, request: "GET index.html HTTP/2.0", upstream: "fastcgi://unix:/opt/bitnami/php/var/run/www.sock:", host: "localhost", referrer: "localhost/index.php"

By configuring the PHP-FPM timeout setting, you may prevent this issue. But it may cause another problem. As the default timeout for NGINX is 60 seconds, if the PHP-FPM timeout is raised above this limit - it can result in 504 Gateway Error. This can be stopped by raising the timeout value to 90 seconds as we have done here –

http {
...
    fastcgi_buffers 16 16k;
    fastcgi_buffer_size 64k;
    fastcgi_connect_timeout 180;
    fastcgi_send_timeout 180;
    fastcgi_read_timeout 180;

}

You can then restart PHP-FPM by typing the following code –

sudo serice php-fpm restart

You can also reload NGINX to make the changes applicable by using this code –

nginx -s reload

PHP-FPM Server Reached Max Children Settings

The error is often encountered when the application server takes too long to respond to a request. This may be due to the following reasons –

  • Many concurrent visitors on the site increasing the site’s traffic way too much
  • Poor code and buggy scripts leading to slow execution of the PHP program
  • The setting of max_children is very low inside the php-fpm config file

To prevent these errors, you have to analyze the server’s resource usage and performance.  

You need to check which resource is taking longer to respond. Additionally, you can increase the number of process in ww.conf file.

How to Handle This Error?

You can check out this error by accessing the php-fpm error log –

tail -f /var/logs/php-fpm.log
sudo nano /etc/php-fpm.d/www.conf

For this, you need to check php-fpm logs. You can use this command –   

tail -f /var/logs/php-fpm.log

Output:

[19-Sep-2020 02:31:21] WARNING: [pool www] server reached pm.max_children setting (15), consider raising it
[19-Sep-2020 02:31:44] WARNING: [pool www] seems busy (you may need to increase pm.start_servers, or pm.min/max_spare_servers), spawning 8 children, there are 9 idle, and 14 total children

To fix this error, you can increase the number of processes. Use the code below –

Default Settings

pm = dynamic
pm.max_children = 5
pm.start_servers = 2
pm.min_spare_servers = 1
pm.max_spare_servers = 3

Updated Value

pm.max_children = 25
pm.start_servers = 10
pm.min_spare_servers = 5
pm.max_spare_servers = 10
pm.max_requests = 500

Conclusion

Now you have an idea of how to handle the 502 Bad Gateway error. Apart from the solutions mentioned above, you must also try changing your browser. You can clear out cookies and cache files. If you are using too many extensions and plugins in your web browser, try disabling them to solve the 502 Bad Gateway issue.