PHP-FPM and Nginx: 502 Bad Gateway

Go To



  • Ubuntu Server 11.10 64 bit
  • Amazon AWS, Ec2, hosted on the cloud
  • t1.micro instance

Before I write anything else, I'd like to state that I've checked both nginx 502 bad gateway and Nginx + PHP-FPM 502 Bad Gateway threads, which unfortunately haven't helped me in this regard.

The issue appears to be rather common: a misconfiguration of nginx or php-fpm can lead to a 502 Bad Gateway error, which is something that I haven't been able to get rid of. Note that this appears even when I go to my domain root, without specifying any particular directory.

I'm running an Amazon EC2 webserver, with port 9000 enabled, port 80 open, etc.

The question in particular is, how can I get rid of this nasty error? Or, better yet, how can I get php5-fpm to actually work.

What I Have Attempted so Far

Mostly consistent editing of configuration files, notably php-fpm.conf and nginx.conf.

i. php-fpm.conf

I've added the following, which hasn't quite helped much:

; Fpm Start ;

;pm.start_servers = 20
;pm.min_spare_servers = 5
;pm.max_spare_servers = 35

Now, afterward I tried including my configuration files:


Which only screwed me even further.

Full Configuration

; FPM Configuration ;

; All relative paths in this configuration file are relative to PHP's install
; prefix (/usr). This prefix can be dynamicaly changed by using the
; '-p' argument from the command line.

; Include one or more files. If glob(3) exists, it is used to include a bunch of
; files from a glob(3) pattern. This directive can be used everywhere in the
; file.
; Relative path can also be used. They will be prefixed by:
;  - the global prefix if it's been set (-p arguement)
;  - /usr otherwise

; Global Options ;

; Pid file
; Note: the default prefix is /var
; Default Value: none
pid = /var/run/

; Error log file
; Note: the default prefix is /var
; Default Value: log/php-fpm.log
error_log = /var/log/php5-fpm.log

; Log level
; Possible Values: alert, error, warning, notice, debug
; Default Value: notice
log_level = notice

; If this number of child processes exit with SIGSEGV or SIGBUS within the time
; interval set by emergency_restart_interval then FPM will restart. A value
; of '0' means 'Off'.
; Default Value: 0
;emergency_restart_threshold = 0

; Interval of time used by emergency_restart_interval to determine when 
; a graceful restart will be initiated.  This can be useful to work around
; accidental corruptions in an accelerator's shared memory.
; Available Units: s(econds), m(inutes), h(ours), or d(ays)
; Default Unit: seconds
; Default Value: 0
emergency_restart_interval = 0

; Time limit for child processes to wait for a reaction on signals from master.
; Available units: s(econds), m(inutes), h(ours), or d(ays)
; Default Unit: seconds
; Default Value: 0
;process_control_timeout = 0

; Send FPM to background. Set to 'no' to keep FPM in foreground for debugging.
; Default Value: yes
daemonize = no

; Fpm Start ;

;pm.start_servers = 20
;pm.min_spare_servers = 5
;pm.max_spare_servers = 35

; Pool Definitions ; 

; Multiple pools of child processes may be started with different listening
; ports and different management options.  The name of the pool will be
; used in logs and stats. There is no limitation on the number of pools which
; FPM can handle. Your system will tell you anyway :)

; To configure the pools it is recommended to have one .conf file per
; pool in the following directory:

ii. nginx.conf

In all honesty this configuration is a smattering of a few websites I've visited, but I can tell you that before this 502 Bad Gateway business, the server was running fine (without PHP working. Period.).

The issue primarily lies in the fact that something is terribly, terribly wrong. And now, when I try to do a service php5-fpm restart, it hangs in what I'm guessing is an infinite loop or something, which I can't even CTRL-C out of.

Full Configuration

user www-data;
worker_processes 1;
pid /var/run/;

events {
    worker_connections 64;
    # multi_accept on;

http {

    # Basic Settings

    sendfile on;
    tcp_nopush off;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    # server_tokens off;

    # server_names_hash_bucket_size 64;
    # server_name_in_redirect off;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    # Logging Settings

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    # Gzip Settings

    gzip on;
    gzip_disable "msie6";

    # gzip_vary on;
    # gzip_proxied any;
    # gzip_comp_level 6;
    # gzip_buffers 16 8k;
    # gzip_http_version 1.1;
    # gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;

    # Virtual Host Configs

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;

    server {
        listen 80;

        location ~ ^(.+\.php)(.*)$ {
            root   /home/wayvac/public;
            fastcgi_pass   unix:/var/run/;  
            #fastcgi_pass; #Un-comment this and comment "fastcgi_pass   unix:/var/run/php-fpm/php-fpm.sock;" if you are not using php-fpm.
            fastcgi_index  index.php;
            set $document_root2 $document_root;
            if ($document_root2 ~ "^(.*\\\\).*?[\\\\|\/]\.\.\/(.*)$") { set $document_root2 $1$2; }
            if ($document_root2 ~ "^(.*\\\\).*?[\\\\|\/]\.\.\/(.*)$") { set $document_root2 $1$2; }
            if ($document_root2 ~ "^(.*\\\\).*?[\\\\|\/]\.\.\/(.*)$") { set $document_root2 $1$2; }
            if ($document_root2 ~ "^(.*\\\\).*?[\\\\|\/]\.\.\/(.*)$") { set $document_root2 $1$2; }
            if ($document_root2 ~ "^(.*\\\\).*?[\\\\|\/]\.\.\/(.*)$") { set $document_root2 $1$2; }
            fastcgi_split_path_info ^(.+\.php)(.*)$;
            fastcgi_param   SCRIPT_FILENAME $document_root2$fastcgi_script_name;
            fastcgi_param   PATH_INFO   $fastcgi_path_info;
            fastcgi_param   PATH_TRANSLATED $document_root2$fastcgi_path_info;
            include fastcgi_params;
            fastcgi_param  DOCUMENT_ROOT      $document_root2;

        access_log /var/log/nginx/access.log;
        error_log /var/log/nginx/error.log;

        location / {
            root /home/wayvac/public;   
            index index.html index.htm index.php;

        location ~* \.(?:ico|css|js|gif|jpe?g|png)$ {
            # Some basic cache-control for static files to be sent to the browser
            expires max;
            add_header Pragma public;
            add_header Cache-Control "public, must-revalidate, proxy-revalidate";

        #include drop.conf;
        #include php.conf;
2012-04-04 01:50
by zeboidlund


If anyone finds this page by encountering the same problem I had, I found the answer here:

For those of you who can't be bothered to click and work it out for themselves... ;)

The Condition:

Ubuntu or Debian server with NGINX and PHP 5.3 works fine but upgrading PHP to 5.4 gives 502 Bad Gateway errors. Looking for services running on port 9000 (typically running netstat -lp or similar) returns nothing.

The fix:

Open /etc/php5/fpm/pool.d/www.conf and make a note of the 'listen' parameter (in my case /var/run/php5-fpm.sock):

; The address on which to accept FastCGI requests.
; Valid syntaxes are:
;   ''    - to listen on a TCP socket to a specific address on
;                            a specific port;
;   'port'                 - to listen on a TCP socket to all addresses on a
;                            specific port;
;   '/path/to/unix/socket' - to listen on a unix socket.
; Note: This value is mandatory.
listen = /var/run/php5-fpm.sock

and replace the fastcgi_pass variable in your vhost with the location you just noted.

So this sample symfony2 configuration (taken from here:

  # pass the PHP scripts to FastCGI server listening on
  location ~ ^/(app|app_dev)\.php(/|$) {
    fastcgi_split_path_info ^(.+\.php)(/.*)$;
    include fastcgi_params;
    fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
    fastcgi_param  HTTPS              off;

becomes this:

  # pass the PHP scripts to FastCGI server at /var/run/php5-fpm.sock
  location ~ ^/(app|app_dev)\.php(/|$) {
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_split_path_info ^(.+\.php)(/.*)$;
    include fastcgi_params;
    fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
    fastcgi_param  HTTPS              off;

Then restart nginx:

sudo /etc/init.d/nginx restart

Note: replace ~ ^/(app|app_dev)\.php(/|$) { with ~ ^/index\.php(/|$) { if you're not on SF2**

Hope this saves someone a little bit of time :)


Of course, you could change the listen = /var/run/php5-fpm.sock to listen = in /etc/php5/fpm/pool.d/www.conf then restart php5-fpm (which would save you from having to change your vhosts), but you have to assume they changed php5-fpm to run through a socket rather than listening on port 9000 for a reason.


If you're still experiencing 502 error see this answer: nginx error connect to php5-fpm.sock failed (13: Permission denied)

2013-01-28 10:40
by nealio82
Unix sockets are only marginally faster and could fail under heavy load - Desmond Hume 2013-08-26 19:41
didn't help, it was already set like that, and I keep experiencing 502 all the time - vsync 2014-03-24 19:15
Bad gateway just means Nginx can't find PHP. Are you sure the php-fpm service is installed and running? Try restarting it if it is running, perhaps it's hanging - nealio82 2014-03-31 21:00
@Nealio I'm using ubuntu server running nginx. do you know where exactly I can find the file referring to # pass the PHP scripts to FastCGI server at /var/run/php5-fpm.sock location ~ ^/(app|app_dev)\.php(/|$) { fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_split_path_info ^(.+\.php)(/.*)$; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param HTTPS off; } - user111671 2014-04-01 22:18
I'm not quite sure what you're asking. Are you saying you don't know where to find the file with that block in? If so, then that'll be whichever vhost file you're setting up, in /etc/nginx/sites-available. If you mean you can't find the file which tells you the location of the socket file (php5-fpm.sock), it should be /etc/php5/fpm/pool.d/www.conf. If it's not there comment back & I'll set up an ubuntu / nginx instance and let you know - nealio82 2014-04-03 08:25
I meet some problem, and need fix the /etc/php5/fpm/pool.d/www.conf on Ubuntu 12.04, but Debian 7.0 is not - Chu-Siang Lai 2014-04-09 06:15
I've just checked on a Debian 7.2 server (default config) and it's definitely there. Can you search for it with find? find / -iname "www.conf - nealio82 2014-04-09 08:26
They seem to have changed this recently and made it so it always uses the original port numbers i.e. 2014-07-10 15:29
Why is this the solution? Changing from TCP to Unix Domain Socket or Unix Domain Socket to TCP does nothing for me? I keep getting 502 gateway errors, and the NGINX log says the "Connection reset by peer while reading response header from upstream", in which upstream is PHP-FPM - CMCDragonkai 2015-12-10 19:30
If you're getting 'connection reset by peer' then it surely must have been talking to PHP-FPM initially for each request, and this solution isn't applicable to your problem (read 'The Condition' at the top of my answer - this isn't a catch-all solution for all problems). I think you probably need to find out why PHP-FPM is dying as it's processing your scripts - nealio82 2016-02-03 10:55
Nailed it :) dud - Crysis 2017-04-07 05:39


Try setting these values, it solves problem in fast-cgi

fastcgi_buffer_size 16k;
fastcgi_buffers 4 16k;
2012-05-22 06:51
by ananthan
This did it for me. It was quite difficult to pin down since the fastcgi error was truncated in the nginx log. Thanks - jrhorn424 2013-09-13 03:58
go ahead and set it to 64k for Symfony2.3 :) the error output of Symfony just seems to overwhelm the buffers.. - Stefan 2013-10-26 15:08
May I ask where(which file) does this code go - Hao 2014-03-12 01:22
@Jusfeel These options should be added to nginx's config file - biphobe 2014-06-08 20:14
What a miracle solution. Thank - jan 2015-10-05 11:33
I applied to Siwapp installed under nginx and it works great! Thank you very much : - akajack 2016-01-26 15:28


I made all this similar tweaks, but from time to time I was getting 501/502 errors (daily).

This are my settings on /etc/php5/fpm/pool.d/www.conf to avoid 501 and 502 nginx errors… The server has 16Gb RAM. This configuration is for a 8Gb RAM server so…

sudo nano /etc/php5/fpm/pool.d/www.conf

then set the following values for

pm.max_children = 70
pm.start_servers = 20
pm.min_spare_servers = 20
pm.max_spare_servers = 35
pm.max_requests = 500

After this changes restart php-fpm

sudo service php-fpm restart
2015-12-22 00:58
by PJunior
ya this worked for me. thank - Richard Torcato 2016-05-25 20:43
this worked for me, great thank - s4suryapal 2017-10-14 06:37


If you met the problem after upgrading php-fpm like me, try this: open /etc/php5/fpm/pool.d/www.conf uncomment the following lines:

listen.owner = www-data = www-data
listen.mode = 0666

then restart php-fpm.

2015-01-30 05:25
by yang
Solved it for me too. The conf file was /etc/php/php-fpm.d/www/conf on Arch Linux. Note that setting permissions to 0666 is probably not suitable for production. Instead, a production server should match the Nginx user and the PHP-FPM user and keep the permissions to 0660 to increase security - conradkdotcom 2016-01-25 22:09


Don't forget that php-fpm is a service. After installing it, make sure you start it:

# service php-fpm start
# chkconfig php-fpm on
2014-06-11 06:45
by Jake Wilson


For anyone else struggling to get to the bottom of this, I tried adjusting timeouts as suggested as I didn't want to stop using Unix sockets...after lots of troubleshooting and not much to go on I found that this issue was being caused by the APC extension that I'd enabled in php-fpm a few months back. Disabling this extension resolved the intermittent 502 errors, easiest way to do this was by commenting out the following line :

;extension =

This did the trick for me!

2015-06-23 18:40
by William Emmerson


The port was changed to 9001 in 5.4, just changing the port from 9000 to 9001 in the nginx conf and in php-fpm configuration worked for me.

2013-08-04 07:07
by Aaron Judd


Hope this tip will save someone else's life. In my case the problem was that I ran out of memory, but only slightly, was hard to think about it. Wasted 3hrs on that. I recommend running:

sudo htop


sudo free -m

...along with running problematic requests on the server to see if your memory doesn't run out. And if it does like in my case, you need to create swap file (unless you already have one).

I have followed this tutorial to create swap file on Ubuntu Server 14.04 and it worked just fine:

2015-02-12 15:37
by Rav


I've also found this error can be caused when writing json_encoded() data to MySQL. To get around it I base64_encode() the JSON. Please not that when decoded, the JSON encoding can change values. Nb. 24 can become 24.00

2015-11-09 22:53
by Lionel Morrison


All right after trying every solution on the web I ended up figuare out the issue using very simple method , first I cheked php-fpm err log

cat /var/log/php5-fpm.log 

and the most repeated error was

" WARNING: [pool www] server reached pm.max_children setting (5), consider raising it "

I edit PHP-fpm pools setting

nano /etc/php5/fpm/pool.d/www.conf

I chenged This Line

pm.max_children = 5

To new Value

pm.max_children = 10

BTW I'm using low end VPS with 128MB ram As everyone else I was thinkin redusing pm.max_children will make my server run faster consume less memory , but the setting we using were too low tho even start PHP-fpm process . I hope this help others since I found this after 24 hour testing and failing , ever my webhost support were not able to solve the issue .

2016-04-29 15:39
by Salem


You should see the error log. By default, its location is in /var/log/nginx/error.log

In my case, 502 get way because of:

GET /app_dev.php HTTP/1.1", upstream: "fastcgi://unix:/run/php/php7.0-fpm.sock:", host: "symfony2.local"
2016/05/25 11:57:28 [error] 22889#22889: *3 upstream sent too big header while reading response header from upstream, client:, server: symfony2.local, request: "GET /app_dev.php HTTP/1.1", upstream: "fastcgi://unix:/run/php/php7.0-fpm.sock:", host: "symfony2.local"
2016/05/25 11:57:29 [error] 22889#22889: *3 upstream sent too big header while reading response header from upstream, client:, server: symfony2.local, request: "GET /app_dev.php HTTP/1.1", upstream: "fastcgi://unix:/run/php/php7.0-fpm.sock:", host: "symfony2.local"
2016/05/25 11:57:29 [error] 22889#22889: *3 upstream sent too big header while reading response header from upstream, client:, server: symfony2.local, request: "GET /app_dev.php HTTP/1.1", upstream: "fastcgi://unix:/run/php/php7.0-fpm.sock:", host: "symfony2.local"

When we know exactly what is wrong, then fix it. For these error, just modify the buffer:

fastcgi_buffers 16 512k; 
fastcgi_buffer_size 512k;
2016-05-25 05:04
by De Nguyen


I'm very late to this game, but my problem started when I upgraded php on my server. I was able to just remove the .socket file and restart my services. Then, everything worked. Not sure why it made a difference, since the file is size 0 and the ownership and permissions are the same, but it worked.

2017-05-28 15:44
by humanity


Before messing with Nginx config, try to disable ChromePHP first.

1 - Open app/config/config_dev.yml

2 - Comment these lines:

    type:   chromephp
    level:  info

ChromePHP pack the debug info json-encoded in the X-ChromePhp-Data header, which is too big for the default config of nginx with fastcgi.

2017-08-17 14:33
by Lucas Bustamante
Sources: [1] [2] - Lucas Bustamante 2017-08-17 14:33


In your NGINX vhost file, in location block which processes your PHP files (usually location ~ \.php$ {) through FastCGI, make sure you have next lines:

proxy_buffer_size          128k;
proxy_buffers              4 256k;
proxy_busy_buffers_size    256k;
fastcgi_buffer_size        16k;
fastcgi_buffers            4 16k;

After that don't forget to restart fpm and nginx.


NGINX vhost paths

  • /etc/nginx/sites-enabled/ - Linux
  • '/usr/local/etc/nginx/sites-enabled/' - Mac

Restart NGINX:

  • sudo service nginx restart - Linux
  • brew service restart nginx - Mac

Restart FPM:

Determine fpm process name: - systemctl list-unit-files | grep fpm - Linux - brew services list | grep php - Mac

and then restart it with:

  • sudo service <service-name> restart - Linux
  • brew services restart <service-name> - Mac
2018-05-23 17:32
by М.Б.