PHP-FPM 和 Nginx:502 错误网关

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10003978/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 21:07:57  来源:igfitidea点击:

PHP-FPM and Nginx: 502 Bad Gateway

nginxamazon-ec2php

提问by zeboidlund

Configuration

配置

  • Ubuntu Server 11.10 64 bit
  • Amazon AWS, Ec2, hosted on the cloud
  • t1.micro instance
  • Ubuntu 服务器 11.10 64 位
  • 托管在云上的 Amazon AWS、Ec2
  • t1.micro 实例

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

在我写其他任何东西之前,我想声明我已经检查了nginx 502 bad gatewayNginx + PHP-FPM 502 Bad Gateway线程,不幸的是,这对我没有帮助。

The issue appears to be rather common: a misconfiguration of nginx or php-fpm can lead to a 502 Bad Gatewayerror, 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.

这个问题似乎很常见:nginx 或 php-fpm 的错误配置会导致502 Bad Gateway错误,这是我无法摆脱的。请注意,即使我转到我的域 root 时也会出现这种情况,而没有指定任何特定目录。

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

我正在运行 Amazon EC2 网络服务器,启用端口 9000,打开端口 80 等。

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

特别的问题是,我怎样才能摆脱这个讨厌的错误?或者,更好的,我怎样才能php5-fpm实际工作

What I Have Attempted so Far

到目前为止我所做的尝试

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

大部分配置文件的一致编辑,特别是php-fpm.confnginx.conf.

i.php-fpm.conf

一世。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:

现在,之后我尝试包含我的配置文件:

include=/etc/php5/fpm/*.conf

include=/etc/php5/fpm/*.conf

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
;include=/etc/php5/fpm/*.conf

;;;;;;;;;;;;;;;;;;
; Global Options ;
;;;;;;;;;;;;;;;;;;

[global]
; Pid file
; Note: the default prefix is /var
; Default Value: none
pid = /var/run/php5-fpm.pid

; 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:
include=/etc/php5/fpm/pool.d/*.conf

ii. nginx.conf

ii. 配置文件

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.).

老实说,这个配置是我访问过的几个网站的一小部分,但我可以告诉你,在这个 502 Bad Gateway 业务之前,服务器运行良好(没有 PHP 工作。期间。)。

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-Cout of.

问题主要在于某些事情非常非常错误。现在,当我尝试执行 a 时service php5-fpm restart,它挂在我猜测是无限循环或其他东西中,我什CTRL至无法C摆脱。

Full Configuration

完整配置

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

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;
        server_name ec2-xx-xx-xx-xx.compute-x.amazonaws.com;

        location ~ ^(.+\.php)(.*)$ {
            root   /home/wayvac/public;
            fastcgi_pass   unix:/var/run/php5-fpm.pid;  
            #fastcgi_pass   127.0.0.1:9000; #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 ; }
            if ($document_root2 ~ "^(.*\\).*?[\\|\/]\.\.\/(.*)$") { set $document_root2 ; }
            if ($document_root2 ~ "^(.*\\).*?[\\|\/]\.\.\/(.*)$") { set $document_root2 ; }
            if ($document_root2 ~ "^(.*\\).*?[\\|\/]\.\.\/(.*)$") { set $document_root2 ; }
            if ($document_root2 ~ "^(.*\\).*?[\\|\/]\.\.\/(.*)$") { set $document_root2 ; }
            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;
    }
}

回答by nealio82

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 -lpor similar) returns nothing.

带有 NGINX 和 PHP 5.3 的 Ubuntu 或 Debian 服务器工作正常,但将 PHP 升级到 5.4 会出现 502 Bad Gateway 错误。查找在端口 9000 上运行的服务(通常正在运行netstat -lp或类似)不返回任何内容。

The fix:

修复:

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

打开/etc/php5/fpm/pool.d/www.conf并记下 'listen' 参数(在我的例子中/var/run/php5-fpm.sock):

; The address on which to accept FastCGI requests.
; Valid syntaxes are:
;   'ip.add.re.ss:port'    - 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.

并将您的 vhost 中的 fastcgi_pass 变量替换为您刚刚记下的位置。

So this sample symfony2 configuration (taken from here):

所以这个示例 symfony2 配置(取自这里):

  # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
  location ~ ^/(app|app_dev)\.php(/|$) {
    fastcgi_pass   127.0.0.1:9000;
    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:

然后重启nginx:

sudo /etc/init.d/nginx restart

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

注意:如果您不在 SF2 上,替换~ ^/(app|app_dev)\.php(/|$) {~ ^/index\.php(/|$) {**

Hope this saves someone a little bit of time :)

希望这可以为某人节省一点时间:)

Edit

编辑

Of course, you could change the listen = /var/run/php5-fpm.sockto listen = 127.0.0.1:9000in /etc/php5/fpm/pool.d/www.confthen 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.

当然,您可以将其更改listen = /var/run/php5-fpm.socklisten = 127.0.0.1:9000in/etc/php5/fpm/pool.d/www.conf然后重新启动 php5-fpm(这将使您不必更改虚拟主机),但是您必须假设他们将 php5-fpm 更改为通过套接字运行,而不是在端口 9000 上侦听原因。

Edit2

编辑2

If you're still experiencing 502 error see this answer.

如果您仍然遇到 502 错误,请参阅此答案

回答by ananthan

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

尝试设置这些值,它解决了 fast-cgi 中的问题

fastcgi_buffer_size 16k;
fastcgi_buffers 4 16k;

回答by PJunior

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

我做了所有这些类似的调整,但我不时收到 501/502 错误(每天)。

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

这是我在/etc/php5/fpm/pool.d/www.conf上的设置,以避免 501 和 502 nginx 错误……服务器有 16Gb RAM。此配置适用于 8Gb RAM 服务器,因此……

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

在此更改后重新启动 php-fpm

sudo service php-fpm restart

回答by yang

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:

如果你和我一样在升级 php-fpm 后遇到问题,试试这个: open /etc/php5/fpm/pool.d/www.conf 取消注释以下几行:

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

then restart php-fpm.

然后重新启动php-fpm。

回答by Jake Wilson

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

别忘了这php-fpm是一项服务。安装后,请确保启动它:

# service php-fpm start
# chkconfig php-fpm on

回答by William Emmerson

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 :

对于其他努力想弄清楚这个问题的人,我尝试按照建议调整超时,因为我不想停止使用 Unix 套接字......经过大量故障排除后,我发现这个问题是造成的通过几个月前我在 php-fpm 中启用的 APC 扩展。禁用此扩展解决了间歇性 502 错误,最简单的方法是注释掉以下行:

;extension = apc.so

This did the trick for me!

这对我有用!

回答by Rav

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:

希望这个技巧能挽救别人的生命。就我而言,问题是我的内存不足,但只是轻微的,很难去想它。浪费了3个小时。我建议运行:

sudo htop

or

或者

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: http://www.cyberciti.biz/faq/ubuntu-linux-create-add-swap-file/

我已经按照本教程在 Ubuntu Server 14.04 上创建交换文件,它工作得很好:http: //www.cyberciti.biz/faq/ubuntu-linux-create-add-swap-file/

回答by Aaron Judd

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.

端口在 5.4 中更改为 9001,只需在 nginx conf 和 php-fpm 配置中将端口从 9000 更改为 9001 对我有用。

回答by Alexander Gavriliuk

Maybe this answer will help:

也许这个答案会有所帮助:

nginx error connect to php5-fpm.sock failed (13: Permission denied)

nginx 错误连接到 php5-fpm.sock 失败(13:权限被拒绝)

The solution was to replace www-data with nginx in /var/www/php/fpm/pool.d/www.conf

解决方案是在 /var/www/php/fpm/pool.d/www.conf 中用 nginx 替换 www-data

And respectively modify the socket credentials:

并分别修改socket凭证:

$ sudo chmod nginx:nginx /var/run/php/php7.2-fpm.sock

回答by Salem

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

好吧,在尝试了网络上的所有解决方案后,我最终使用非常简单的方法解决了问题,首先我检查了 php-fpm 错误日志

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

我编辑 PHP-fpm 池设置

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_childrenwill 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 .

顺便说一句,我正在使用具有 128MB ram 的低端 VPS 就像其他人一样,我认为重用pm.max_children将使我的服务器运行得更快,消耗更少的内存,但我们使用的设置太低,甚至无法启动 PHP-fpm 进程。我希望这能帮助其他人,因为我在 24 小时测试和失败后发现了这一点,我的网络主机支持无法解决问题。