首页 文章

PHP-FPM和Nginx:502 Bad Gateway

提问于
浏览
75

Configuration

  • Ubuntu Server 11.10 64位

  • 亚马逊AWS,Ec2,托管在 Cloud 端

  • t1.micro实例

在我写任何其他内容之前,我已经检查了nginx 502 bad gatewayNginx + PHP-FPM 502 Bad Gateway个线程,遗憾的是这些线程在这方面没有帮助我 .

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

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

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

What I Have Attempted so Far

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

i. php-fpm.conf

我添加了以下内容,这些内容并没有多大帮助:

;;;;;;;;;;;;;
; Fpm Start ;
;;;;;;;;;;;;;

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

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

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

这让我更进一步 .

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

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

问题主要在于事情非常严重,非常错误 . 现在,当我尝试做一个 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 $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;
    }
}

14 回答

  • 151

    如果有人通过遇到同样的问题找到了这个页面,我在这里找到了答案:http://www.howtoforge.com/installing-nginx-with-php5-and-php-fpm-and-mysql-support-lemp-on-ubuntu-12.04-lts

    对于那些不能打扰点击并为自己解决的人...;)

    The Condition:

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

    The fix:

    打开 /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
    

    并使用您刚才记下的位置替换vhost中的fastcgi_pass变量 .

    所以这个示例symfony2配置(取自这里:http://wiki.nginx.org/Symfony):

    # 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;
      }
    

    成为这个:

    # 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;
      }
    

    然后重启nginx:

    sudo /etc/init.d/nginx restart
    

    Note: 如果您不在SF2 **,请将 ~ ^/(app|app_dev)\.php(/|$) { 替换为 ~ ^/index\.php(/|$) { **

    希望这能节省一点时间:)

    Edit

    当然,你可以在 /etc/php5/fpm/pool.d/www.conf 中将 listen = /var/run/php5-fpm.sock 更改为 listen = 127.0.0.1:9000 然后重新启动php5-fpm(这样可以避免更改你的vhost),但是你必须假设他们改变了php5-fpm来运行套接字而不是监听端口9000是有原因的 .

    Edit2

    如果您仍然遇到502错误,请参阅以下答案:nginx error connect to php5-fpm.sock failed (13: Permission denied)

  • 0

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

    fastcgi_buffer_size 16k;
    fastcgi_buffers 4 16k;
    
  • 3

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

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

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

    然后为其设置以下值

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

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

    sudo service php-fpm restart
    
  • 28

    如果您像我一样升级php-fpm后遇到问题,请尝试以下操作:打开/etc/php5/fpm/pool.d/www.conf取消注释以下行:

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

    然后重启php-fpm .

  • 0

    不要忘记 php-fpm 是一项服务 . 安装后,请确保启动它:

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

    对于其他任何想要深究这一点的人,我尝试按照建议调整超时,因为我不想停止使用Unix套接字......经过大量的故障排除并且没有多少继续下去我发现这个问题是由于通过几个月前我在php-fpm中启用的APC扩展 . 禁用此扩展程序解决了间歇性502错误,最简单的方法是通过注释掉以下行:

    ;extension = apc.so
    

    这对我有用!

  • 10

    端口在5.4中更改为9001,只是在nginx conf中将端口从9000更改为9001,并且在php-fpm配置中为我工作 .

  • 0

    希望这个提示可以拯救别人的生命 . 在我的情况下,问题是我的内存不足,但只是轻微,很难想到它 . 浪费了3个小时 . 我建议跑步:

    sudo htop
    

    要么

    sudo free -m
    

    ...以及在服务器上运行有问题的请求,看看你的内存是否没用完 . 如果确实如此就像在我的情况下,你需要创建交换文件(除非你已经有一个) .

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

  • 0

    我还发现在将json_encoded()数据写入MySQL时可能会导致此错误 . 为了解决这个问题,我将base64_encode()改为JSON . 请注意,解码时,JSON编码可以更改值 . 铌 . 24可以变成24.00

  • 2

    在网上尝试每个解决方案之后,我最终用非常简单的方法来解决问题,首先我讨厌了php-fpm错误日志

    cat /var/log/php5-fpm.log
    

    最重复的错误是

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

    我编辑PHP-fpm池设置

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

    我想这条线

    pm.max_children = 5
    

    为了新的 Value

    pm.max_children = 10
    

    顺便说一句,我正在使用128MB内存的低端VPS正如我所想的那样,我认为重新使用 pm.max_children 将使我的服务器运行更快,消耗更少的内存,但我们使用的设置太低甚至无法启动PHP-fpm进程 . 我希望这可以帮助别人,因为我在24小时测试和失败后发现这一点,我的webhost支持无法解决问题 .

  • 1

    您应该看到错误日志 . 默认情况下,其位置位于/var/log/nginx/error.log中

    就我而言,502因为:

    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: 127.0.0.1, 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: 127.0.0.1, 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: 127.0.0.1, server: symfony2.local, request: "GET /app_dev.php HTTP/1.1", upstream: "fastcgi://unix:/run/php/php7.0-fpm.sock:", host: "symfony2.local"
    

    当我们确切地知道什么是错的时候,然后解决它 . 对于这些错误,只需修改缓冲区:

    fastcgi_buffers 16 512k; 
    fastcgi_buffer_size 512k;
    
  • 0

    我这个游戏已经很晚了,但是当我在服务器上升级php时,我的问题就出现了 . 我能够删除.socket文件并重新启动我的服务 . 一切顺利 . 不确定为什么它会有所不同,因为文件大小为0,所有权和权限相同,但它有效 .

  • 4

    在弄乱Nginx配置之前,请先尝试禁用ChromePHP .

    1 - 打开app / config / config_dev.yml

    2 - 评论这些行:

    chromephp:
        type:   chromephp
        level:  info
    

    ChromePHP将调试信息json编码打包在X-ChromePhp-Data标头中,这对于使用fastcgi的nginx的默认配置来说太大了 .

  • 0

    在您的NGINX vhost文件中,在通过FastCGI处理PHP文件(通常为 location ~ \.php$ { )的位置块中,请确保您有下一行:

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

    之后不要忘记重启fpm和nginx .


    Additional:

    NGINX虚拟路径

    • /etc/nginx/sites-enabled/ - Linux

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

    重启NGINX:

    • sudo service nginx restart - Linux

    • brew service restart nginx - Mac

    重启FPM:

    确定fpm进程名称: - systemctl list-unit-files | grep fpm - Linux - brew services list | grep php - Mac

    然后重启它:

    • sudo service <service-name> restart - Linux

    • brew services restart <service-name> - Mac

相关问题