Understanding the 502 – Bad Gateway error

Throughout my experience, the error that has no proper indication about its origin was called 502 – Bad Gateway. In this post, we will understand what it is and why it occurs. The Mozilla developer guide states that,

The HyperText Transfer Protocol (HTTP) 502 Bad Gateway server error response code indicates that the server, while acting as a gateway or proxy, received an invalid response from the upstream server.

It simply means suppose you have a proxy server let’s call it NGINX. It received an invalid response. By invalid response it means there is an error in the upstream server.

In the image above, you can observe that NGINX, acting as a proxy server, attempts to access the Node.js server, which serves as the upstream server. However, a MySQL connection problem arises. NGINX will receive this as invalid response coming from node(.js) server. Because it’s an invalid response, the NGINX server will send a 502 – Bad Gateway response back to the user.

This is just an example. There are so many reasons that can be responsible for this Bad Gateway error. Such as,

  • Your NGINX server is not running or not activated. You can check this by putting this command sudo systemctl status nginx this will show the current status of your NGINX server. If it is not started yet try this command sudo systemctl start nginx.
  • Incorrect Firewall Configuration can cause this error. For example, issues like port blocking or IP address restrictions can cause the problem.
  • Incorrect DNS Resolution can create the issue.
  • Overloaded request to the upstream server in our case node(.js) server, can cause this issue.

So now the question arrives, how to fix?

There are number of ways available,

  • Review the Firewall configuration. Check to see if there are any rules in place that might be blocking specific protocols like HTTP or HTTPS.
  • Review the IP of the upstream server.
  • Review and test the upstream server. You can view the logs and try to understand if there are any errors.

Sometimes, there isn’t just one reason for the 502 Bad Gateway error. You might need to check a few things to find out what’s causing it

I hope you understand something. Please leave a comment if you have any questions.

Leave a Comment

Your email address will not be published. Required fields are marked *