php-fpm 高并发、502解决方案

php-fpm 配置文件生成

file_exists('php-fpm-conf/prod') or mkdir('php-fpm-conf/prod', 0777, true);
file_exists('php-fpm-conf/test') or mkdir('php-fpm-conf/test', 0777, true);

for ($i = 1; $i <= 10; $i ++) {
    $ii = "0000$i";
    $ii = substr($ii, strlen($ii) - 2);

    $name = "/var/run/php-cgi-{$ii}.sock";

    $proConf = <<<TAG

[www_sockets_{$ii}]

user = nobody
group = nobody
listen = {$name}
listen.backlog = 1024
listen.owner = nginx
listen.group = nginx
listen.mode = 0660

pm = dynamic
pm.max_children = 256
pm.start_servers = 1
pm.min_spare_servers = 1
pm.max_spare_servers = 10
pm.process_idle_timeout = 10s
pm.max_requests = 102400

slowlog = /var/log/php-fpm/\$pool.log.slow
request_slowlog_timeout = 5
rlimit_files = 102400

TAG;
    file_put_contents("php-fpm-conf/prod/www_sockets_{$ii}.conf", $proConf);

    $devConf = <<<TAG
{$proConf}

env[ENVIRONMENT] = development

TAG;
    file_put_contents("php-fpm-conf/test/www_sockets_{$ii}.conf", $devConf);

    echo "        server unix:{$name}       weight=5;\n";
}

nginx配置

...
    upstream phpbackend {
        server unix:/var/run/php-cgi-01.sock       weight=5;
        server unix:/var/run/php-cgi-02.sock       weight=5;
        server unix:/var/run/php-cgi-03.sock       weight=5;
        server unix:/var/run/php-cgi-04.sock       weight=5;
        server unix:/var/run/php-cgi-05.sock       weight=5;
        server unix:/var/run/php-cgi-06.sock       weight=5;
        server unix:/var/run/php-cgi-07.sock       weight=5;
        server unix:/var/run/php-cgi-08.sock       weight=5;
        server unix:/var/run/php-cgi-09.sock       weight=5 backup;
        server unix:/var/run/php-cgi-10.sock       weight=5 backup;
    }

...

      location ~.*.php($|/){
            ...
            fastcgi_pass   phpbackend;
            ....
        }
...