Nginx с PHP-FastCGI => 502 Bad Gateway

Mr.Tokio

Гуру форума
Регистрация
17 Дек 2007
Сообщения
289
Реакции
60
Люди добрые помажите разобраться, а то сами мы не местные))))
Вообщем смысл ситуации таков есть связка Nginx с PHP-FastCGI и MySQL в Ubuntu 10.04.
Есть сайт + под-домен! все на 80 порт идет связка PHP+Nginx идет через lighttpd
примерно так ставил:
1)
Код:
aptitude install lighttpd
Вот так убирал с 80 порта чтобы nginx не сбивал
2)
Код:
update-rc.d -f lighttpd remove
и вот так ставил его в автозагрузку
3)
Код:
/usr/bin/spawn-fcgi -a 127.0.0.1 -p 9000 -u www-data -g www-data -f /usr/bin/php5-cgi -P /var/run/fastcgi-php.pid
вот default nginx
Код:
# You may add here your
# server {
#	...
# }
# statements for each of your virtual hosts
server {
	listen   80 default;
	server_name  localhost;
	access_log  /var/log/nginx/localhost.access.log;
	location / {
		root   /var/www/;
		index  index.html index.htm index.php;
	}
	location /doc {
		root   /usr/share;
		autoindex on;
		allow 127.0.0.1;
		deny all;
	}
	location /images {
		root   /usr/share;
		autoindex on;
	}
        location ~ \.php$ {
                fastcgi_pass   127.0.0.1:9000;
                fastcgi_index  index.php;
                fastcgi_param  SCRIPT_FILENAME  /var/www/$fastcgi_script_name;
                include        fastcgi_params;
        }
	#error_page  404  /404.html;
	# redirect server error pages to the static page /50x.html
	#
	#error_page   500 502 503 504  /50x.html;
	#location = /50x.html {
	#	root   /var/www/nginx-default;
	#}
	# proxy the PHP scripts to Apache listening on 127.0.0.1:80
	#
	#location ~ \.php$ {
		#proxy_pass   http://127.0.0.1;
	#}
	# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
	#
	#location ~ \.php$ {
		#fastcgi_pass   127.0.0.1:9000;
		#fastcgi_index  index.php;
		#fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
		#includefastcgi_params;
	#}
	# deny access to .htaccess files, if Apache's document root
	# concurs with nginx's one
	#
	#location ~ /\.ht {
		#deny  all;
	#}
}
# another virtual host using mix of IP-, name-, and port-based configuration
#
#server {
#listen   8000;
#listen   somename:8080;
#server_name  somename  alias  another.alias;
#location / {
#root   html;
#index  index.html index.htm;
#}
#}
# HTTPS server
#
#server {
#listen   443;
#server_name  localhost;
#ssl  on;
#ssl_certificate  cert.pem;
#ssl_certificate_key  cert.key;
#ssl_session_timeout  5m;
#ssl_protocols  SSLv2 SSLv3 TLSv1;
#ssl_ciphers  ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP;
#ssl_prefer_server_ciphers   on;
#location / {
#root   html;
#index  index.html index.htm;
#}
#}
А вот сонфиг поддомена
Код:
server {
     listen   80;
     server_name  a.domen.ru;
     access_log  /var/log/nginx/bigbluebutton.access.log;
	 # Handle RTMPT (RTMP Tunneling).  Forwards requests
	 # to Red5 on port 5080
      location ~ (/open/|/close/|/idle/|/send/) {
          proxy_pass         http://127.0.0.1:5080;
          proxy_redirect     off;
          proxy_set_header   X-Forwarded-For   $proxy_add_x_forwarded_for;
          client_max_body_size       10m;
          client_body_buffer_size    128k;
          proxy_connect_timeout      90;
          proxy_send_timeout         90;
          proxy_read_timeout         90;
          proxy_buffering            off;
      }
	 # Handle desktop sharing tunneling.  Forwards
	 # requests to Red5 on port 5080.
       location /deskshare {
           proxy_pass         http://127.0.0.1:5080;
           proxy_redirect     default;
           proxy_set_header   X-Forwarded-For   $proxy_add_x_forwarded_for;
           client_max_body_size       10m;
           client_body_buffer_size    128k;
           proxy_connect_timeout      90;
           proxy_send_timeout         90;
           proxy_read_timeout         90;
           proxy_buffer_size          4k;
           proxy_buffers              4 32k;
           proxy_busy_buffers_size    64k;
           proxy_temp_file_write_size 64k;
           include    fastcgi_params;
       }
	 # Handle request to bbb-web running within Tomcat.  This is for
	 # the BBB-API and Presentation.
       location /bigbluebutton {
           proxy_pass         http://127.0.0.1:8080;
           proxy_redirect     default;
           proxy_set_header   X-Forwarded-For   $proxy_add_x_forwarded_for;
	# Allow 30M uploaded presentation document.
           client_max_body_size       30m;
           client_body_buffer_size    128k;
           proxy_connect_timeout      90;
           proxy_send_timeout         90;
           proxy_read_timeout         90;
           proxy_buffer_size          4k;
           proxy_buffers              4 32k;
           proxy_busy_buffers_size    64k;
           proxy_temp_file_write_size 64k;
           include    fastcgi_params;
       }
	# BigBlueButton landing page.
        location / {
          root   /var/www/bigbluebutton-default;
          index  index.html index.htm;
        }
	# BigBlueButton.html is here so we can expire it every 1 minute to
        # prevent caching.
        location /client/BigBlueButton.html {
                root    /var/www/bigbluebutton;
                index  index.html index.htm;
                expires 1m;
        }
	# BigBlueButton Flash client.
        location /client {
                root    /var/www/bigbluebutton;
                index  index.html index.htm;
        }
	# Include specific rules for record and playback
        include /etc/bigbluebutton/nginx/*;
        #error_page  404  /404.html;
        # Redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
                root   /var/www/nginx-default;
        }
}
В чем косяк? косяк в том что переодически отваливаеться FastCGI и после ребута он удаляеться из автозагрузки!!! кто подскажет где косяк???
 
3)
Код:
/usr/bin/spawn-fcgi -a 127.0.0.1 -p 9000 -u www-data -g www-data -f /usr/bin/php5-cgi -P /var/run/fastcgi-php.pid
вот default nginx
Не совсем понятно, куда именно в автозагрузку поставлен запуск FastCGI, эта команда запустит потоки fast-cgi один раз, для автозагрузки нужно добавлять в /etc/init.d или еще куда-то.
Насчет "иногда слетает fcgi" - слишком расплывчато, нужно смотреть потребление памяти воркерами fast-cgi, ошибки в логе итд.
 
Эхххх сам отвечу
делаем такого демона для загрузки!
Код:
#! /bin/sh
### BEGIN INIT INFO
# Provides: spawn-fcgi
# Required-Start: $all
# Required-Stop: $all
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: starts FastCGI
# Description: starts FastCGI with spawn-fcgi
### END INIT INFO
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
NAME=spawn-fcgi
PID=/var/run/spawn-fcgi.pid
DAEMON_OPTS="-f /usr/bin/spawn-fcgi -a 127.0.0.1 -p 9000 -u www-data -g www-data -P $PID"
. /lib/lsb/init-functions
test -x $DAEMON || exit 
set -e
case "$1" in
start)
log_daemon_msg "spawn-fcgi starting"
start-stop-daemon --start --pidfile $PID --exec $DAEMON -- $DAEMON_OPTS
echo "done."
;;
stop)
log_daemon_msg "spawn-fcgi stopping"
start-stop-daemon --stop --pidfile $PID --retry 5
rm -f $PID
echo "done."
;;
restart)
echo "Stopping $NAME: "
start-stop-daemon --stop --pidfile $PID --retry 5
rm -f $PID
echo "done..."
sleep 1
echo "Starting $NAME: "
start-stop-daemon --start --pidfile $PID --exec $DAEMON -- $DAEMON_OPTS
echo "done."
;;
*)
echo "Usage: /etc/init.d/$NAME {start|stop|restart}" >&2
exit 1
;;
esac
exit
и будет с вами счастье!
 
Нашел способ еще лучше может кому и пригодиться!!!
1)Добавим php в автозагрузку. Для чего оздаем скрипт '/etc/init.d/php-fastcgi' следующего содержания:
Код:
#! /bin/sh
### BEGIN INIT INFO
# Provides: php-fastcgi
# Required-Start: $all
# Required-Stop: $all
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Start and stop php-cgi in external FASTCGI mode
# Description: Start and stop php-cgi in external FASTCGI mode
### END INIT INFO

# Author: Kurt Zankl <kz@xon.uni.cc>

# Do NOT "set -e"

PATH=/sbin:/usr/sbin:/bin:/usr/bin
DESC="php-cgi in external FASTCGI mode"
NAME=php-fastcgi
DAEMON=/usr/bin/php-cgi
PIDFILE=/var/run/$NAME.pid
scriptNAME=/etc/init.d/$NAME

# Exit if the package is not installed
[ -x "$DAEMON" ] || exit 0

# Read configuration variable file if it is present
[ -r /etc/default/$NAME ] && . /etc/default/$NAME

# Load the VERBOSE setting and other rcS variables
. /lib/init/vars.sh

# Define LSB log_* functions.
# Depend on lsb-base (>= 3.0-6) to ensure that this file is present.
. /lib/lsb/init-functions

# If the daemon is not enabled, give the user a warning and then exit,
# unless we are stopping the daemon
if [ "$START" != "yes" -a "$1" != "stop" ]; then
log_warning_msg "To enable $NAME, edit /etc/default/$NAME and set START=yes"
exit 0
fi

# Process configuration
export PHP_FCGI_CHILDREN PHP_FCGI_MAX_REQUESTS
DAEMON_ARGS="-q -b $FCGI_HOST:$FCGI_PORT"

do_start()
{
# Return
# 0 if daemon has been started
# 1 if daemon was already running
# 2 if daemon could not be started
start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON --test > /dev/null || return 1
start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON --background --make-pidfile --chuid $EXEC_AS_USER --startas $DAEMON -- $DAEMON_ARGS || return 2
}

do_stop()
{
# Return
# 0 if daemon has been stopped
# 1 if daemon was already stopped
# 2 if daemon could not be stopped
# other if a failure occurred
start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --pidfile $PIDFILE > /dev/null # --name $DAEMON
RETVAL="$?"
[ "$RETVAL" = 2 ] && return 2
# Wait for children to finish too if this is a daemon that forks
# and if the daemon is only ever run from this initscript.
# If the above conditions are not satisfied then add some other code
# that waits for the process to drop all resources that could be
# needed by services started subsequently. A last resort is to
# sleep for some time.
start-stop-daemon --stop --quiet --oknodo --retry=0/30/KILL/5 --exec $DAEMON
[ "$?" = 2 ] && return 2
# Many daemons don't delete their pidfiles when they exit.
rm -f $PIDFILE
return "$RETVAL"
}

case "$1" in
start)
[ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC" "$NAME"
do_start
case "$?" in
0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
esac
;;
stop)
[ "$VERBOSE" != no ] && log_daemon_msg "Stopping $DESC" "$NAME"
do_stop
case "$?" in
0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
esac
;;
restart|force-reload)
log_daemon_msg "Restarting $DESC" "$NAME"
do_stop
case "$?" in
0|1)
do_start
case "$?" in
0) log_end_msg 0 ;;
1) log_end_msg 1 ;; # Old process is still running
*) log_end_msg 1 ;; # Failed to start
esac
;;
*)
# Failed to stop
log_end_msg 1
;;
esac
;;
*)
echo "Usage: $scriptNAME {start|stop|restart|force-reload}" >&2
exit 3
;;
esac
2) Делаем исполяемым:
Код:
chmod 755 /etc/init.d/php-fastcgi
3)Создаем другой файл '/etc/default/php-fastcgi', чтобы мы могли контролировать php-fastcgi (слушать порты, получать количество дочерних процессов и другие запросы), такого содержания:
Код:
#
# Settings for php-cgi in external FASTCGI Mode
#

# Should php-fastcgi run automatically on startup? (default: no)
START=yes

# Which user runs PHP? (default: www-data)
EXEC_AS_USER=www-data

# Host and TCP port for FASTCGI-Listener (default: localhost:9000)
FCGI_HOST=localhost
FCGI_PORT=9000

# Environment variables, which are processed by PHP
PHP_FCGI_CHILDREN=5
PHP_FCGI_MAX_REQUESTS=1000
4)Запускаем php-fastcgi:
Код:
/etc/init.d/php-fastcgi start
5)Добавляем в автозагрузку:
Код:
update-rc.d php-fastcgi defaults
 
так меня поперло))) сам спросил и сам 3 раза ответил))))
ну вот еще скрипт для запуска через сокеты php:
-пихаем в /etc/init.d/php-fcgid
-не забываем про chmod 755 /etc/init.d/php-fcgid
- и делаем исполняемым update-rc.d php-fcgid defaults


Код:
#!/bin/sh
#
# Author: Till Klampaeckel <till@php.net>
#
# Credits
#
#  * original script: http://unix.derkeiler.com/Mailing-Lists/FreeBSD/questions/2007-09/msg00468.html
#  * improved: http://till.klampaeckel.de/blog/archives/30-PHP-performance-III-Running-nginx.html
#  * all linux start script fu inspired by CouchDB's start script (by Noah Slater)
#

SCRIPT_OK=0
SCRIPT_ERROR=1

DESCRIPTION="php-fcgi super-duper-control thing"
NAME=php-fgcid
SCRIPT_NAME=$(basename $0)

WWW_GROUP=www-data
PHP_CGI=/usr/bin/php-cgi

phpfcgid_users="johndoe jandoe"
phpfcgid_children="2"
phpfcgid_tmpdir="/tmp"
phpfcgid_requests="100"

log_daemon_msg () {
    echo $@
}

log_end_msg () {
    # Dummy function to be replaced by LSB library.

    if test "$1" != "0"; then
        echo "Error with $DESCRIPTION: $NAME"
    fi
    return $1
}

phpfcgid_start() {
    echo "Starting $NAME with $phpfcgid_children children (req: $phpfcgid_requests)."

    export PHP_FCGI_CHILDREN=$phpfcgid_children
    export PHP_FCGI_MAX_REQUESTS=$phpfcgid_requests

    for user in ${phpfcgid_users}; do
        socketdir="${phpfcgid_tmpdir}/.fastcgi.${user}"
        mkdir -p ${socketdir}
        chown ${user}:${WWW_GROUP} ${socketdir}
        chmod 0750 ${socketdir}
        su -m ${user} -c "${PHP_CGI} -b ${socketdir}/socket&"
    done
}

phpfcgid_stop() {
    echo "Stopping $NAME."
    pids=`pgrep php-cgi`
    pkill php-cgi
}

phpfcgid_status() {
    log_daemon_msg "To be implemented: status"
    log_end_msg $SCRIPT_ERROR
}


parse_script_option_list () {

    case "$1" in
        start)
            log_daemon_msg "Starting $DESCRIPTION" $NAME
            if phpfcgid_start; then
                log_end_msg $SCRIPT_OK
            else
                log_end_msg $SCRIPT_ERROR
            fi
            ;;
        stop)
            log_daemon_msg "Stopping $DESCRIPTION" $NAME
            if phpfcgid_stop; then
                log_end_msg $SCRIPT_OK
            else
                log_end_msg $SCRIPT_ERROR
            fi
            ;;
        restart|force-reload)
            log_daemon_msg "Restarting $DESCRIPTION" $NAME
            if phpfcgid_stop; then
                if phpfcgid_start; then
                    log_end_msg $SCRIPT_OK
                else
                    log_end_msg $SCRIPT_ERROR
                fi
            else
                log_end_msg $SCRIPT_ERROR
            fi
            ;;
        status)
            phpfcgid_status
            ;;
        *)
            cat << EOF >&2
Usage: $SCRIPT_NAME {start|stop|restart|force-reload|status}
EOF
            exit $SCRIPT_ERROR
            ;;
    esac
}

parse_script_option_list $@
 
Назад
Сверху