Solving “502 Bad Gateway” with nginx & php-fpm

After upgrading php-fpm, my PHP-based sites were returning “502 Bad Gateway” errors. Here’s how I managed to solve it.

Check to make sure that php-fpm is running with ps auxww | grep php – if you can’t see any php-fpm processes in the output, then you may need to re-install php-fpm. If php-fpm is running okay, then skip this first step.

sudo apt-get remove php5 php5-cgi php5-fpm
sudo apt-get install php5 php5-cgi php5-fpm

The thing to notice here is that the order in which you install the packages is important. In the past I have found that installing them in the wrong order causes the packages to be configured incorrectly.

Next, get php-fpm to listen on the correct host/port. In /etc/php5/fpm/pool.d/www.conf change the following line from:

listen = /var/run/php5-fpm.sock

To:

listen = 127.0.0.1:9000

Restart php-fpm with sudo /etc/init.d/php-fpm restart and everything should work normally again.

  • Simon

    Thanx, that’s work !

  • http://drewnoakes.com/ Drew Noakes

    Thank you. In my case, I actually had to do the opposite of what you described. My new install was configured to listen via TCP where nginx was attempting to connect via sockets.

    • http://twitter.com/ifsorbuts Sander Versluys

      Same here! This article and comments helped though! Thanks!

  • Sander

    Wow, thank you! I’m new to Linux and I’ve been looking for a solution to this problem for 2 days now and this works perfect! One thing I’d like to know, what’s the difference between this “.sock” path and the ip:port value?

    • http://twitter.com/Joseph_Wynn Joseph Wynn

      Hi Sander,

      Unix sockets use the local filesystem to create a connection and perform slightly better because they don’t have the overhead of the TCP/IP stack. Internet sockets (IP:port) are more flexible and portable.

      I don’t think the performance difference is noticeable unless the server is handling very high traffic.