How to fix Nginx 502 Bad Getaway Error on Ubuntu 14.04

One of my Fiverr clients contacted me few day ago saying that some of his sites started to give 502 Bad Getaway Errors and he wanted me to look in to it. He used my LEMP stack tutorial to set up his server. So I was happy to help. And I think the solution would help most users who are following my tutorials. So i’m going to explain how I fixed Nginx 502 Bad Getaway Error on Ubuntu 14.04

About the error

Client had about 10 websites hosted on the server. It was a 1GB droplet from DigitalOcean. Only few sites were giving 502 errors. Mostly WordPress blogs and a Prosper202 instance. HTML sites were working fine.

What really happened

The error 502 means that the web server can’t communicate with the upstream, in this case php5-fpm. More information will be available on the Nginx error log. Since I had separate error logs for each virtual host, I opened a log file of a problematic site with this command,

nano /var/log/nginx/example.com.error.log

And this is what I found,

2015/08/30 06:53:36 (error) 1557#0: *2460362 connect() to unix:/var/run/php5-fpm.sock failed (11: Resource temporarily unavailable) while connecting to upstream, client: xxx.xxx.xx.xx, server: hostname, request: "POST /xmlrpc.php HTTP/1.1", upstream: "fastcgi://unix:/var/run/php5-fpm.sock:", host: "hostname"

There were hundreds of lines of this error message. It gives a clear picture of what’s happening. As it says, connection to php-fpm.sock was failed. It says that the Resource (php-fpm.sock) is temporarily unavailable. This means it’s getting a high load and it’s busy. Its problems on high-load cases are well-known.

The Solution

Using unix sockets is slightly faster since it provides you direct network access without any TCP/IP overhead. On the down side, it is not as scalable as TCP/IP. Nginx will throw 502 errors when the sockets have been depleted. In such a case you can either tweak the OS settings to accommodate the larger connection pool or just switch to TCP/IP.

So I switched to TCP/IP instead of unix socket. Please follow the tutorial Switching to TCP/IP from Unix Socket to fix your server. Since you’re configuring php5-fpm to use tcp/ip, you should change fastcgi_pass unix:/var/run/php5-fpm.sock; to fastcgi_pass 127.0.0.1:9000; on Nginx virtual host file as well.

Tharindu

Hey!! I'm Tharindu. I'm from Sri Lanka. I'm a part time freelancer and this is my blog where I write about everything I think might be useful to readers. If you read a tutorial here and want to hire me, contact me here.

Related Articles

Leave a Reply

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

Back to top button

We use cookies to give you the best online experience. By agreeing you accept the use of cookies in accordance with our cookie policy.