502 Bad Gateway Error means that your proxy server (NGINX) was unable to get a valid response from its upstream (backend) servers. There are various reasons why this happens, and multiple ways to fix it. Let us take a look at how to fix 502 bad gateway error in NGINX.
How to Fix 502 Bad Gateway Error in NGINX
Here are the steps to fix 502 Bad Gateway error in NGINX.
Reasons for 502 Bad Gateway Responses
There are mainly 3 reasons why NGINX gives 502 Bad Gateway Errors
1. Domain Name cannot be resolved
This happens when the domain name entered by website visitors doesn’t resolve to a proper IP, or doesn’t resolve to an IP at all. This can happen when you change DNS settings for your domain name. Remember that these changes take some time to propagate and until then your visitors will keep seeing this message.
2. Upstream Server Down
If NGINX is unable to reach your back end servers (e.g Apache), due to connectivity issues or simply because it is down, then too this error will show up.
3. Firewall blocking connections
If there’s a firewall on your origin (back end/upstream) server that blocks inbound connections from your proxy NGINX server then you will see this error. This might also be because of some security plugins on your Apache server. Some times it might also be due to DDOS prevention systems overreacting.
This is what a 502 Bad Gateway error looks like.
How to Diagnose 502 Bad Gateway Error
The easiest way to diagnose this error is to search for “502” response code in your web server’s log files.
Apache log files are located at /var/log/apache2/error.log and NGINX error log is located at /var/log/nginx/error.log
Use the following commands to identify which requests resulted in 502 bad gateway error, and investigate further.
$ sudo grep 502 /var/log/apache2/error.log $ sudo grep 502 /var/log/nginx/error/log
How to Solve 502 Bad Gateway Error
If you are web developer or a webmaster, you can do the following to fix the problem.
- Check if your domain name properly resolves to a valid IP address using a DNS test tool
- Check if your server is actually reachable using a ping test or trace route
- Check your firewall to see if there are too many blocked requests
- If you use CloudFlare, disable it temporarily because it shows 502 response once you reach a certain limit of traffic.
If you are a website visitor and face this problem, then you can try the following:
- Do a hard refresh of your browser. You will find this option in Settings/Preferences of your browser
- Clear your browser cache and delete cookies
- Restart your laptop or network connection
- Change your DNS servers. Try the Google Public DNS settings