How To Fix 502 Bad Gateway on Nginx Web Server

Nginx Stacked Logo

Error message like 502 Bad Gateway on Nginx web server is usually related to PHP-FPM service. But not all 502 Bad Gateway errors are related to PHP-FPM services, sometimes it’s caused by an internal error from the Nginx web server itself.

I recently encountered a 502 Bad Gateway error on my Nginx web server, and I have tried to fix it from the PHP-FPM service side, but that didn’t fix the problem.

So I tried to solve it with a different approach. Yes, finally I can fix it from the Nginx server side. Well, if you facing 502 bad gateway issue on the Nginx web server, try to solve with increasing open file limits inside your virtual machine.

1.) First of all, check your current Nginx open file limits rule.

$ cat /proc/$(cat /var/run/ | grep open.files
Max open files 1024 4096 files

2.) After that, create a nginx.service.d folder inside /etc/systemd/system/ directory

$ mkdir -p /etc/systemd/system/nginx.service.d

3.) And then, you must create a new file called “nginx.conf”

$ nano /etc/systemd/system/nginx.service.d/nginx.conf

4.) And then put the following snippet code:


5.) Let’s restart system daemon and Nginx services.

$ systemctl daemon-reload
$ systemctl restart nginx.service

6.) Let’s cek your Maximum Number Of Open Files.

$ cat /proc/$(cat /var/run/ | grep open.files
Max open files 65536 65536 files