PHP-FPM 및 Nginx : 502 불량 게이트웨이


78

구성

  • Ubuntu Server 11.10 64 비트
  • 클라우드에서 호스팅되는 Amazon AWS, Ec2
  • t1.micro 인스턴스

다른 글을 쓰기 전에 nginx 502 불량 게이트웨이Nginx + PHP-FPM 502 불량 게이트웨이 스레드를 모두 확인했음을 말씀 드리고 싶습니다.이 스레드는 불행히도 이와 관련하여 도움이되지 않았습니다.

이 문제는 다소 일반적인 것 같습니다. nginx 또는 php-fpm을 잘못 구성하면 502 Bad Gateway오류가 발생할 수 있는데, 이는 제가 제거 할 수 없었던 것입니다. 특정 디렉토리를 지정하지 않고 내 도메인 루트로 이동할 때도 나타납니다 .

포트 9000이 활성화되고 포트 80이 열린 상태로 Amazon EC2 웹 서버를 실행하고 있습니다.

특히 문제는이 불쾌한 오류를 어떻게 제거 할 수 있습니까? 또는 더 나은 아직, 어떻게 얻을 수 php5-fpm실제로 작동 .

내가 지금까지 시도한 것

구성 파일, 특히 php-fpm.confnginx.conf.

나는. php-fpm.conf

다음을 추가했지만 그다지 도움이되지 않았습니다.

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

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

이제 나중에 구성 파일을 포함 해 보았습니다.

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

더 이상 나를 망쳤습니다.

전체 구성

;;;;;;;;;;;;;;;;;;;;;
; 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아웃.

전체 구성

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

답변:


151

누구든지 내가 가진 것과 동일한 문제가 발생 하여이 페이지를 찾은 경우 여기 에서 답을 찾았습니다 .

클릭하고 스스로 해결하는 것을 귀찮게 할 수없는 분들을 위해 ...;)

조건:

NGINX 및 PHP 5.3이 설치된 Ubuntu 또는 Debian 서버는 정상적으로 작동하지만 PHP를 5.4로 업그레이드하면 502 Bad Gateway 오류가 발생합니다. 포트 9000 (일반적으로 실행 중이 netstat -lp거나 유사)에서 실행중인 서비스를 검색하면 아무 것도 반환되지 않습니다.

수정 사항 :

/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 구성 ( 여기 에서 가져옴 ) :

  # 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

참고 : 교체 ~ ^/(app|app_dev)\.php(/|$) {와 함께 ~ ^/index\.php(/|$) {당신이 SF2에하지 않으면 **

이것이 누군가에게 약간의 시간을 절약하기를 바랍니다. :)

편집하다

물론, 당신은 변경할 수 listen = /var/run/php5-fpm.sock하기 listen = 127.0.0.1:9000/etc/php5/fpm/pool.d/www.conf(당신의 가상 호스트를 변경할 필요에서 당신을 절약 할 수있는) 한 다음 다시 시작 PHP5-FPM,하지만 당신은 그들이 소켓을 통해 실행보다는에 대해 포트 9000에서 수신 대기하는 PHP5-FPM을 변경 가정해야 이유.

편집 2

여전히 502 오류가 발생하는 경우이 답변을 참조하세요 .


2
Unix 소켓은 약간 더 빠르며 과부하시 실패 할 수 있습니다. drupal.org/node/1635622#comment-6814968
Desmond Hume

도움이되지 않았고, 이미 그렇게 설정되었고, 502 번을 계속 경험하고 있습니다.
vsync 2014 년

나쁜 게이트웨이는 Nginx가 PHP를 찾을 수 없음을 의미합니다. php-fpm 서비스가 설치되어 실행되고 있습니까? 실행중인 경우 다시 시작해보십시오.
nealio82 2014 년

@Nealio 저는 nginx를 실행하는 우분투 서버를 사용하고 있습니다. 내가 참조하는 파일을 정확히 어디에서 찾을 수 있는지 알고 # 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

1
항상 원래의 포트 번호가 즉 사용 그래서 그들은 그것을 최근에 변경 한 것 및 제작127.0.0.1:9000
marksyzm

28

이 값을 설정하면 fast-cgi에서 문제가 해결됩니다.

fastcgi_buffer_size 16k;
fastcgi_buffers 4 16k;

이것은 나를 위해 해냈습니다. fastcgi 오류가 nginx 로그에서 잘 렸기 때문에 고정하기가 매우 어려웠습니다. 감사!
jrhorn424 2013-09-13

1
계속해서 Symfony2.3에 대해 64k로 설정하십시오. :) Symfony의 오류 출력이 버퍼를 압도하는 것 같습니다 ...
Stefan

2
@Jusfeel이 옵션은 nginx의 설정 파일에 추가되어야합니다.
biphobe 2014-06-08

이 얼마나 기적적인 해결책. 감사합니다
1

nginx에 설치된 Siwapp에 적용했는데 잘 작동합니다! 대단히 감사합니다 :)
akajack

11

이 모든 유사한 조정을 수행했지만 때때로 501/502 오류가 발생했습니다.

이것은 501 및 502 nginx 오류를 방지하기위한 /etc/php5/fpm/pool.d/www.conf의 설정입니다 . 서버에는 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

4

나처럼 php-fpm을 업그레이드 한 후 문제가 발생하면 다음을 시도하십시오. open /etc/php5/fpm/pool.d/www.conf 다음 줄의 주석 처리를 제거하십시오.

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

그런 다음 php-fpm을 다시 시작하십시오.


나를 위해 해결했습니다. conf 파일은 /etc/php/php-fpm.d/www/confArch Linux에 있습니다. 권한을 0666로 설정하는 것은 프로덕션에 적합하지 않을 수 있습니다. 대신 프로덕션 서버는 Nginx 사용자 및 PHP-FPM 사용자와 일치하고 0660보안을 강화 하기 위해 권한을 유지해야합니다 .
conradkleinespel

3

그것이 php-fpm서비스 라는 것을 잊지 마십시오 . 설치 후 시작해야합니다.

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

2

이 문제를 해결하기 위해 고군분투하는 다른 사람을 위해 Unix 소켓 사용을 중단하고 싶지 않았기 때문에 제안 된대로 시간 제한을 조정 해 보았습니다 ... 많은 문제 해결 후 계속 진행하지 않고이 문제가 발생하고 있음을 발견했습니다. 몇 달 전에 php-fpm에서 활성화 한 APC 확장에 의해. 이 확장 기능을 비활성화하면 간헐적 인 502 오류가 해결되었습니다.이 작업을 수행하는 가장 쉬운 방법은 다음 줄을 주석 처리하는 것입니다.

;extension = apc.so

이것은 나를 위해 트릭을했습니다!


1

포트는 5.4에서 9001로 변경되었으며 nginx conf에서 포트를 9000에서 9001로 변경하고 php-fpm 구성에서 저에게 효과적이었습니다.


1

이 팁이 다른 사람의 생명을 구하기를 바랍니다. 제 경우 문제는 메모리가 부족하다는 것이었지만 약간만 생각하기 어려웠습니다. 그것에 3 시간을 낭비했습니다. 다음을 실행하는 것이 좋습니다.

sudo htop

또는

sudo free -m

... 메모리가 부족하지 않은지 확인하기 위해 서버에서 문제가있는 요청을 실행하는 것과 함께. 그리고 제 경우에는 스왑 파일을 만들어야합니다 (이미 가지고 있지 않은 경우).

이 튜토리얼을 따라 Ubuntu Server 14.04에서 스왑 파일을 만들었으며 제대로 작동했습니다. http://www.cyberciti.biz/faq/ubuntu-linux-create-add-swap-file/


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

또한이 오류는 json_encoded () 데이터를 MySQL에 쓸 때 발생할 수 있음을 발견했습니다. 그것을 우회하기 위해 JSON을 base64_encode ()합니다. 디코딩 할 때 JSON 인코딩이 값을 변경할 수 있습니다. Nb. 24는 24.00이 될 수 있습니다.


0

웹에서 모든 솔루션을 시도한 후 매우 간단한 방법을 사용하여 문제를 해결했습니다. 먼저 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

새로운 가치로

pm.max_children = 10

BTW 나는 128MB 램과 함께 로우 엔드 VPS를 사용하고 있습니다. 다른 사람들과 마찬가지로 redusing pm.max_children은 내 서버가 더 빨리 실행되도록 만들 것입니다. 나는 이것이 내가 24 시간의 테스트와 실패 후에 이것을 발견했기 때문에 다른 사람들에게 도움이되기를 바란다. 나의 웹 호스트 지원은 문제를 해결할 수 없었다.


0

이 게임에 너무 늦었지만 서버에서 PHP를 업그레이드했을 때 문제가 시작되었습니다. .socket 파일을 제거하고 서비스를 다시 시작할 수있었습니다. 그런 다음 모든 것이 작동했습니다. 파일 크기가 0이고 소유권과 권한이 동일하기 때문에 왜 차이가 있었는지 확실하지 않지만 작동했습니다.


0

Nginx 구성을 엉망으로 만들기 전에 먼저 ChromePHP를 비활성화하십시오.

1-app / config / config_dev.yml 열기

2-다음 행에 주석을 달십시오.

chromephp:
    type:   chromephp
    level:  info

ChromePHP는 X-ChromePhp-Data 헤더에 json으로 인코딩 된 디버그 정보를 압축합니다. 이는 fastcgi를 사용하는 nginx의 기본 구성에 비해 너무 큽니다.



0

NGINX 가상 호스트 파일의 location ~ \.php$ {FastCGI를 통해 PHP 파일 (일반적으로 )을 처리하는 위치 블록에 다음 줄이 있는지 확인합니다.

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

그 후에 fpm과 nginx를 다시 시작하는 것을 잊지 마십시오.


추가 :

NGINX 가상 호스트 경로

  • /etc/nginx/sites-enabled/ -리눅스
  • '/ usr / local / etc / nginx / sites-enabled /'-Mac

NGINX를 다시 시작합니다.

  • sudo service nginx restart -리눅스
  • brew service restart nginx - 맥

FPM 다시 시작 :

fpm 프로세스 이름 결정 : systemctl list-unit-files | grep fpm--Linux brew services list | grep php--Mac

다음으로 다시 시작하십시오.

  • sudo service <service-name> restart -리눅스
  • brew services restart <service-name> - 맥

0

이 답변이 도움이 될 것입니다.

nginx 오류 php5-fpm.sock에 연결하지 못했습니다 (13 : 권한 거부 됨).

해결책은 /var/www/php/fpm/pool.d/www.conf에서 www-data를 nginx로 바꾸는 것이 었습니다.

그리고 각각 소켓 자격 증명을 수정합니다.

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

nginx 오류가 php5-fpm.sock에 연결하지 못한 경우 올바른 솔루션입니다 (13 : 권한 거부 됨)
Florin
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.