php-fpm 配置

实践:

2、

任务:配置多端口的php-fpm

1、进入配置目录,同php.ini目录
[lighthouse@VM-4-12-centos etc]$ nl  php-fpm.conf
     1  ;;;;;;;;;;;;;;;;;;;;;
     2  ; FPM Configuration ;
     3  ;;;;;;;;;;;;;;;;;;;;;

     4  ; All relative paths in this configuration file are relative to PHP's install
     5  ; prefix (/www/server/php/72). This prefix can be dynamically changed by using the
     6  ; '-p' argument from the command line.

     7  ;;;;;;;;;;;;;;;;;;
     8  ; Global Options ;
     9  ;;;;;;;;;;;;;;;;;;

    10  [global]
    11  ; Pid file
    12  ; Note: the default prefix is /www/server/php/72/var
    13  ; Default Value: none
    14  ;pid = run/php-fpm.pid

    15  ; Error log file
    16  ; If it's set to "syslog", log is sent to syslogd instead of being written
    17  ; into a local file.
    18  ; Note: the default prefix is /www/server/php/72/var
    19  ; Default Value: log/php-fpm.log
    20  ;error_log = log/php-fpm.log
    21  ; syslog_facility is used to specify what type of program is logging the
    22  ; message. This lets syslogd specify that messages from different facilities
    23  ; will be handled differently.
    24  ; See syslog(3) for possible values (ex daemon equiv LOG_DAEMON)
    25  ; Default Value: daemon
    26  ;syslog.facility = daemon

    27  ; syslog_ident is prepended to every message. If you have multiple FPM
    28  ; instances running on the same server, you can change the default value
    29  ; which must suit common needs.
    30  ; Default Value: php-fpm
    31  ;syslog.ident = php-fpm

    32  ; Log level
    33  ; Possible Values: alert, error, warning, notice, debug
    34  ; Default Value: notice
    35  ;log_level = notice

    36  ; If this number of child processes exit with SIGSEGV or SIGBUS within the time
    37  ; interval set by emergency_restart_interval then FPM will restart. A value
    38  ; of '0' means 'Off'.
    39  ; Default Value: 0
    40  ;emergency_restart_threshold = 0
    41  ; Interval of time used by emergency_restart_interval to determine when
    42  ; a graceful restart will be initiated.  This can be useful to work around
    43  ; accidental corruptions in an accelerator's shared memory.
    44  ; Available Units: s(econds), m(inutes), h(ours), or d(ays)
    45  ; Default Unit: seconds
    46  ; Default Value: 0
    47  ;emergency_restart_interval = 0

    48  ; Time limit for child processes to wait for a reaction on signals from master.
    49  ; Available units: s(econds), m(inutes), h(ours), or d(ays)
    50  ; Default Unit: seconds
    51  ; Default Value: 0
    52  ;process_control_timeout = 0

    53  ; The maximum number of processes FPM will fork. This has been designed to control
    54  ; the global number of processes when using dynamic PM within a lot of pools.
    55  ; Use it with caution.
    56  ; Note: A value of 0 indicates no limit
    57  ; Default Value: 0
    58  ; process.max = 128

    59  ; Specify the nice(2) priority to apply to the master process (only if set)
    60  ; The value can vary from -19 (highest priority) to 20 (lowest priority)
    61  ; Note: - It will only work if the FPM master process is launched as root
    62  ;       - The pool process will inherit the master process priority
    63  ;         unless specified otherwise
    64  ; Default Value: no set
    65  ; process.priority = -19

    66  ; Send FPM to background. Set to 'no' to keep FPM in foreground for debugging.
    67  ; Default Value: yes
    68  ;daemonize = yes


    69  ; Set open file descriptor rlimit for the master process.
    70  ; Default Value: system defined value
    71  ;rlimit_files = 1024

    72  ; Set max core size rlimit for the master process.
    73  ; Possible Values: 'unlimited' or an integer greater or equal to 0
    74  ; Default Value: system defined value
    75  ;rlimit_core = 0

    76  ; Specify the event mechanism FPM will use. The following is available:
    77  ; - select     (any POSIX os)
    78  ; - poll       (any POSIX os)
    79  ; - epoll      (linux >= 2.5.44)
    80  ; - kqueue     (FreeBSD >= 4.1, OpenBSD >= 2.9, NetBSD >= 2.0)
    81  ; - /dev/poll  (Solaris >= 7)
    82  ; - port       (Solaris >= 10)
    83  ; Default Value: not set (auto detection)
    84  ;events.mechanism = epoll

    85  ; When FPM is built with systemd integration, specify the interval,
    86  ; in seconds, between health report notification to systemd.
    87  ; Set to 0 to disable.
    88  ; Available Units: s(econds), m(inutes), h(ours)
    89  ; Default Unit: seconds
    90  ; Default value: 10
    91  ;systemd_interval = 10

    92  ;;;;;;;;;;;;;;;;;;;;
    93  ; Pool Definitions ;
    94  ;;;;;;;;;;;;;;;;;;;;

    95  ; Multiple pools of child processes may be started with different listening
    96  ; ports and different management options.  The name of the pool will be
    97  ; used in logs and stats. There is no limitation on the number of pools which
    98  ; FPM can handle. Your system will tell you anyway :)

    99  ; Include one or more files. If glob(3) exists, it is used to include a bunch of
   100  ; files from a glob(3) pattern. This directive can be used everywhere in the
   101  ; file.
   102  ; Relative path can also be used. They will be prefixed by:
   103  ;  - the global prefix if it's been set (-p argument)
   104  ;  - /www/server/php/72 otherwise
   105  include=/www/server/php/72/etc/php-fpm.d/*.conf
注意最后一行105行
[lighthouse@VM-4-12-centos etc]$ tree php-fpm.d/
php-fpm.d/
├── dzq.app.com-fpm.conf
├── www.conf.default
└── z.app.com-fpm.conf

[lighthouse@VM-4-12-centos php-fpm.d]$ nl dzq.app.com-fpm.conf
     1  ; Start a new pool named 'www'.
     2  ; the variable $pool can be used in any directive and will be replaced by the
     3  ; pool name ('www' here)
     4  [dzq.app.com]


    23  ; The address on which to accept FastCGI requests.
    24  ; Valid syntaxes are:
    25  ;   'ip.add.re.ss:port'    - to listen on a TCP socket to a specific IPv4 address on
    26  ;                            a specific port;
    27  ;   '[ip:6:addr:ess]:port' - to listen on a TCP socket to a specific IPv6 address on
    28  ;                            a specific port;
    29  ;   'port'                 - to listen on a TCP socket to all addresses
    30  ;                            (IPv6 and IPv4-mapped) on a specific port;
    31  ;   '/path/to/unix/socket' - to listen on a unix socket.
    32  ; Note: This value is mandatory.
    33  listen = 127.0.0.1:19000

2、nginx
不同端口,做相应的fastcgi_pass配置
        location ~ \.php$ {
            fastcgi_index index.php;
            fastcgi_pass 127.0.0.1:19000;

            #    fastcgi_pass unix:/tmp/php-cgi-72.sock;
            include fastcgi.conf;

            # 传递脚本文件请求的路径;
            # SCRIPT_FILENAME变量是php-fpm可识别的脚本名称;对应的$fastcgi_script_name变量是Nginx定义的脚本名称. $document_root变量是Nginx配置的根目录即root 指定的路径.本文配置当中可理解为,document_root= /usr/share/nginx/wordpress
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        }

3、运行结果
[lighthouse@VM-4-12-centos php-fpm.d]$ ps -ef | grep fpm
lightho+  9240  3349  0 00:57 pts/0    00:00:00 grep --color=auto fpm
root     32751     1  0 00:27 ?        00:00:00 php-fpm: master process (/www/server/php/72/etc/php-fpm.conf)
www      32752 32751  0 00:27 ?        00:00:04 php-fpm: pool dzq.app.com
www      32753 32751  0 00:27 ?        00:00:04 php-fpm: pool dzq.app.com
www      32754 32751  0 00:27 ?        00:00:00 php-fpm: pool z.app.com
www      32755 32751  0 00:27 ?        00:00:00 php-fpm: pool z.app.com
[lighthouse@VM-4-12-centos php-fpm.d]$

  

1、

fastcgi.conf


fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
fastcgi_param  QUERY_STRING       $query_string;
fastcgi_param  REQUEST_METHOD     $request_method;
fastcgi_param  CONTENT_TYPE       $content_type;
fastcgi_param  CONTENT_LENGTH     $content_length;

fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
fastcgi_param  REQUEST_URI        $request_uri;
fastcgi_param  DOCUMENT_URI       $document_uri;
fastcgi_param  DOCUMENT_ROOT      $document_root;
fastcgi_param  SERVER_PROTOCOL    $server_protocol;
fastcgi_param  REQUEST_SCHEME     $scheme;
fastcgi_param  HTTPS              $https if_not_empty;

fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
fastcgi_param  SERVER_SOFTWARE    nginx/$nginx_version;

fastcgi_param  REMOTE_ADDR        $remote_addr;
fastcgi_param  REMOTE_PORT        $remote_port;
fastcgi_param  SERVER_ADDR        $server_addr;
fastcgi_param  SERVER_PORT        $server_port;
fastcgi_param  SERVER_NAME        $server_name;

# PHP only, required if PHP was built with --enable-force-cgi-redirect
fastcgi_param  REDIRECT_STATUS    200;
 
 
php-fpm.conf
[global]
pid = /www/server/php/72/var/run/php-fpm.pid
error_log = /www/server/php/72/var/log/php-fpm.log
log_level = notice

[www]
listen =19000
listen.backlog = 8192
listen.allowed_clients = 127.0.0.1
listen.owner = www
listen.group = www
listen.mode = 0666
user = www
group = www
pm = dynamic
pm.status_path = /phpfpm_72_status
pm.max_children = 50
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 10
request_terminate_timeout = 100
request_slowlog_timeout = 30
slowlog = var/log/slow.log
 
 
 
nginx.conf
 
    fastcgi_connect_timeout 300;
    fastcgi_send_timeout 300;
    fastcgi_read_timeout 300;
    fastcgi_buffer_size 64k;
    fastcgi_buffers 4 64k;
    fastcgi_busy_buffers_size 128k;
    fastcgi_temp_file_write_size 256k;
    fastcgi_intercept_errors on;

    gzip on;
 
 
 
 
    server {
        server_name a.test.com;
        index index.php index.html;
        root /www/wwwroot/code/dzq_latest_install/public;
 
        location / {
            try_files $uri $uri/ /index.php?$query_string;
        }
        location ~ \.php$ {
            fastcgi_index index.php;
            fastcgi_pass 127.0.0.1:19000;

            #    fastcgi_pass unix:/tmp/php-cgi-72.sock;
            include fastcgi.conf;

            # 传递脚本文件请求的路径;
            # SCRIPT_FILENAME变量是php-fpm可识别的脚本名称;对应的$fastcgi_script_name变量是Nginx定义的脚本名称. $document_root变量是Nginx配置的根目录即root 指定的路径.本文配置当中可理解为,document_root= /usr/share/nginx/wordpress
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        }
 
        access_log /www/wwwlogs/php-access.log;
        error_log /www/wwwlogs/php-error.log;
    }
 
 
 PHP-FPM 使用(含多站点多端口) - Cinlap Soft - 博客园 https://www.cnblogs.com/cinlap/p/12059912.html

PHP-FPM 使用

PHP-FPM

是在 Linux 环境下用来管理调度 PHP 执行的调度器,源码安装时会自动安装,PHP 安装可参考Centos 下安装 PHP (新)

查看版本

# php-fpm -v

启动

# php-fpm -c php.ini -y php-fpm.conf

重启

# php-fpm restart
或
# kill -USR2 `cat /usr/local/php/var/run/php-fpm.pid`

扩展

# /etc/init.d/php-fpm { start/stop/restart/reload... }
或
# /service php-fpm { start/stop/restart/reload... }

service 命令就是调用 /etc/init.d 目录下的脚本文件,这种方式其实就是对 kill 方式的一种封装

信号

信号作用
INT 立即终止
QUIT 平滑终止
USR1 重新打开日志文件
USR2 重启(平滑重载所有 worker 进程并重新载入配置和二进制模块)

如何在同一台主机下运行多个 php 配置监听多个端口

场景有 wwwroot/a.com 和 wwwroot/b.com,a.com 使用 9001 端口,b.com 使用 9002 端口。方法是

  • 建立多个配置文件
# cd /usr/local/php/etc/php-fpm.d
# cp www.conf a.com.conf
# vi a.com.conf

修改进程池名,重名的话后面载入的配置会覆盖掉同名的
[www] 修改为 [a.com] 

修改使用的用户名和组
user = nginx(与 nginx.con 相同)
group = nginx

修改侦听
listen = 127.0.0.1:9001

按相同方式,再复制出一个 b.com.conf

  • 命令方式载入多个配置
# /etc/init.d/php-fpm restart --config-php /usr/local/php/etc/php-fpm.d/a.com.conf
# /etc/init.d/php-fpm restart --config-php /usr/local/php/etc/php-fpm.d/b.com.conf

查看一下
# ps aux|grep php-fpm

输出
# root     24425  0.0  0.1 151364  4892 ?        Ss   14:14   0:00 php-fpm: master process (/usr/local/php/etc/php-fpm.conf)
# nginx    24426  0.0  0.1 151348  4448 ?        S    14:14   0:00 php-fpm: pool a.com
# nginx    24427  0.0  0.1 151348  4448 ?        S    14:14   0:00 php-fpm: pool a.com
# nginx    24428  0.0  0.1 151348  5380 ?        S    14:14   0:00 php-fpm: pool b.com
# nginx    24429  0.0  0.1 151348  5380 ?        S    14:14   0:00 php-fpm: pool b.com
# nginx    24430  0.0  0.1 151348  5380 ?        S    14:14   0:00 php-fpm: pool www
# nginx    24431  0.0  0.1 151348  5380 ?        S    14:14   0:00 php-fpm: pool www
# root     24433  0.0  0.0 112712   968 pts/0    S+   14:17   0:00 grep --color=auto php-fpm

可以看到 pool 后面有三个地址,a.com、b.com是自建的两个配置,www 是 www.conf 默认的

参考

多个项目公用php的一个端口好还是一个项目使用一个php端口?
linux启动多个php-fpm
PHP-FPM多实例配置及nginx对应配置

 
 
php-fpm 连接池

[lighthouse@VM-4-12-centos etc]$ pwd
/www/server/php/72/etc
[lighthouse@VM-4-12-centos etc]$ ll -as
total 244
4 drwxr-xr-x 3 root root 4096 Apr 22 00:07 .
4 drwxr-xr-x 10 root root 4096 Apr 15 02:46 ..
4 -rw-r--r-- 1 root root 1272 Apr 15 00:34 pear.conf
72 -rw-r--r-- 1 root root 71650 Apr 21 02:16 php-cli.ini
4 -rw-r--r-- 1 root root 511 Apr 15 03:22 php-fpm.conf
8 -rw-r--r-- 1 root root 4483 Apr 15 00:33 php-fpm.conf.default
4 drwxr-xr-x 2 root root 4096 Apr 22 00:06 php-fpm.d
72 -rw-r--r-- 1 root root 72692 Apr 15 14:47 php.ini
72 -rw-r--r-- 1 root root 72024 Apr 15 00:57 php.iniBAK
[lighthouse@VM-4-12-centos etc]$

;;;;;;;;;;;;;;;;;;;;;
; FPM Configuration ;
;;;;;;;;;;;;;;;;;;;;;

; All relative paths in this configuration file are relative to PHP's install
; prefix (/www/server/php/72). This prefix can be dynamically changed by using the
; '-p' argument from the command line.

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

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

; Error log file
; If it's set to "syslog", log is sent to syslogd instead of being written
; into a local file.
; Note: the default prefix is /www/server/php/72/var
; Default Value: log/php-fpm.log
;error_log = log/php-fpm.log

; syslog_facility is used to specify what type of program is logging the
; message. This lets syslogd specify that messages from different facilities
; will be handled differently.
; See syslog(3) for possible values (ex daemon equiv LOG_DAEMON)
; Default Value: daemon
;syslog.facility = daemon

; syslog_ident is prepended to every message. If you have multiple FPM
; instances running on the same server, you can change the default value
; which must suit common needs.
; Default Value: php-fpm
;syslog.ident = php-fpm

; 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

; The maximum number of processes FPM will fork. This has been designed to control
; the global number of processes when using dynamic PM within a lot of pools.
; Use it with caution.
; Note: A value of 0 indicates no limit
; Default Value: 0
; process.max = 128

; Specify the nice(2) priority to apply to the master process (only if set)
; The value can vary from -19 (highest priority) to 20 (lowest priority)
; Note: - It will only work if the FPM master process is launched as root
; - The pool process will inherit the master process priority
; unless specified otherwise
; Default Value: no set
; process.priority = -19

; Send FPM to background. Set to 'no' to keep FPM in foreground for debugging.
; Default Value: yes
;daemonize = yes

; Set open file descriptor rlimit for the master process.
; Default Value: system defined value
;rlimit_files = 1024

; Set max core size rlimit for the master process.
; Possible Values: 'unlimited' or an integer greater or equal to 0
; Default Value: system defined value
;rlimit_core = 0

; Specify the event mechanism FPM will use. The following is available:
; - select (any POSIX os)
; - poll (any POSIX os)
; - epoll (linux >= 2.5.44)
; - kqueue (FreeBSD >= 4.1, OpenBSD >= 2.9, NetBSD >= 2.0)
; - /dev/poll (Solaris >= 7)
; - port (Solaris >= 10)
; Default Value: not set (auto detection)
;events.mechanism = epoll

; When FPM is built with systemd integration, specify the interval,
; in seconds, between health report notification to systemd.
; Set to 0 to disable.
; Available Units: s(econds), m(inutes), h(ours)
; Default Unit: seconds
; Default value: 10
;systemd_interval = 10

;;;;;;;;;;;;;;;;;;;;
; 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 :)

; 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 argument)
; - /www/server/php/72 otherwise
include=/www/server/php/72/etc/php-fpm.d/*.conf
[lighthouse@VM-4-12-centos etc]$ cat php-fpm.conf.default

 

 

 
 
 

 

php7/etc/php-fpm.d/www.conf 

 nginx php-fpm 高并发优化 - 日记本的回忆 - 博客园 https://www.cnblogs.com/cocoliu/p/8566193.html

PHP-php-fpm配置优化

前言:

  1.少安装PHP模块, 费内存

  2.调高linux内核打开文件数量,可以使用这些命令(必须是root帐号)(我是修改/etc/rc.local,加入ulimit -SHn 51200的)

echo `ulimit -HSn 65536` >> /etc/profile
echo `ulimit -HSn 65536` >> /etc/rc.local
source /etc/profile 

  如果`ulimit -n`数量依旧不多(即上面配置没生效)的话, 可以在 /etc/security/limits.conf 文件最后加上

* soft nofile 51200
* hard nofile 51200

1.与Nginx使用Unix域Socket通信(Nginx和php-fpm在同一台服务器)

  Unix域Socket因为不走网络,的确可以提高Nginx和php-fpm通信的性能,但在高并发时会不稳定。

  Nginx会频繁报错:connect() to unix:/dev/shm/php-fcgi.sock failed (11: Resource temporarily unavailable) while connecting to upstream

  可以通过下面两种方式提高稳定性:
  1)调高nginx和php-fpm中的backlog
       配置方法为:在nginx配置文件中这个域名的server下,在listen 80后面添加default backlog=1024。
       同时配置php-fpm.conf中的listen.backlog为1024,默认为128。
  2)增加sock文件和php-fpm实例数
       再新建一个sock文件,在Nginx中通过upstream模块将请求负载均衡到两个sock文件背后的两套php-fpm实例上。

 

2.php-fpm参数调优

  pm = dynamic; 表示使用哪种进程数量管理方式

    dynamic表示php-fpm进程数是动态的,最开始是pm.start_servers指定的数量,如果请求较多,则会自动增加,保证空闲的进程数不小于pm.min_spare_servers,如果进程数较多,也会进行相应清理,保证多余的进程数不多于pm.max_spare_servers

    static表示php-fpm进程数是静态的, 进程数自始至终都是pm.max_children指定的数量,不再增加或减少

  pm.max_children = 300; 静态方式下开启的php-fpm进程数量
  pm.start_servers = 20; 动态方式下的起始php-fpm进程数量
  pm.min_spare_servers = 5; 动态方式下的最小php-fpm进程数量
  pm.max_spare_servers = 35; 动态方式下的最大php-fpm进程数量

    如果pm为static, 那么其实只有pm.max_children这个参数生效。系统会开启设置数量的php-fpm进程

    如果pm为dynamic, 那么pm.max_children参数失效,后面3个参数生效。系统会在php-fpm运行开始的时候启动pm.start_servers个php-fpm进程,然后根据系统的需求动态在pm.min_spare_servers和pm.max_spare_servers之间调整php-fpm进程数

    那么,对于我们的服务器,选择哪种pm方式比较好呢?事实上,跟Apache一样,运行的PHP程序在执行完成后,或多或少会有内存泄露的问题。这也是为什么开始的时候一个php-fpm进程只占用3M左右内存,运行一段时间后就会上升到20-30M的原因了。

    对于内存大的服务器(比如8G以上)来说,指定静态的max_children实际上更为妥当,因为这样不需要进行额外的进程数目控制,会提高效率。因为频繁开关php-fpm进程也会有时滞,所以内存够大的情况下开静态效果会更好。数量也可以根据 内存/30M 得到,比如8GB内存可以设置为100,那么php-fpm耗费的内存就能控制在 2G-3G的样子。如果内存稍微小点,比如1G,那么指定静态的进程数量更加有利于服务器的稳定。这样可以保证php-fpm只获取够用的内存,将不多的内存分配给其他应用去使用,会使系统的运行更加畅通。

    对于小内存的服务器来说,比如256M内存的VPS,即使按照一个20M的内存量来算,10个php-cgi进程就将耗掉200M内存,那系统的崩溃就应该很正常了。因此应该尽量地控制php-fpm进程的数量,大体明确其他应用占用的内存后,给它指定一个静态的小数量,会让系统更加平稳一些。或者使用动态方式,因为动态方式会结束掉多余的进程,可以回收释放一些内存,所以推荐在内存较少的服务器或VPS上使用。具体最大数量根据 内存/20M 得到。比如说512M的VPS,建议pm.max_spare_servers设置为20。至于pm.min_spare_servers,则建议根据服务器的负载情况来设置,比较合适的值在5~10之间。

    在4G内存的服务器上200就可以(我的1G测试机,开64个是最好的,建议使用压力测试获取最佳值)

  pm.max_requests = 10240;

    nginx php-fpm配置过程中最大问题是内泄漏出问题:服务器的负载不大,但是内存占用迅速增加,很快吃掉内存接着开始吃交换分区,系统很快挂掉!其实根据官方的介绍,php-cgi不存在内存泄漏,每个请求完成后php-cgi会回收内存,但是不会释放给操作系统,这样就会导致大量内存被php-cgi占用。
    

    官方的解决办法是降低PHP_FCGI_MAX_REQUESTS的值,如果用的是php-fpm,对应的php-fpm.conf中的就是max_requests,该值的意思是发送多少个请求后会重启该线程,我们需要适当降低这个值,用以让php-fpm自动的释放内存,不是大部分网上说的51200等等,实际上还有另一个跟它有关联的值max_children,这个是每次php-fpm会建立多少个进程,这样实际上的内存消耗是max_children*max_requests*每个请求使用内存,根据这个我们可以预估一下内存的使用情况,就不用再写脚本去kill了。

  request_terminate_timeout = 30;

    最大执行时间, 在php.ini中也可以进行配置(max_execution_time)

  request_slowlog_timeout = 2; 开启慢日志
  slowlog = log/$pool.log.slow; 慢日志路径

  rlimit_files = 1024; 增加php-fpm打开文件描述符的限制

3.php-fpm的高CPU使用率排查方法

  1)使用top命令, 直接执行top命令后,输入1就可以看到各个核心的CPU使用率。而且通过top -d 0.1可以缩短采样时间

  2)查询php-fpm慢日志

grep -v "^$" www.log.slow.tmp | cut -d " " -f 3,2 | sort | uniq -c | sort -k1,1nr | head -n 50

 

复制代码
复制代码
   5181 run() /www/test.net/framework/web/filters/CFilter.php:41

   5156 filter() /www/test.net/framework/web/filters/CFilterChain.php:131

   2670 = /www/test.net/index.php

   2636 run() /www/test.net/application/controllers/survey/index.php:665

   2630 action() /www/test.net/application/controllers/survey/index.php:18

   2625 run() /www/test.net/framework/web/actions/CAction.php:75

   2605 runWithParams() /www/test.net/framework/web/CController.php:309

   2604 runAction() /www/test.net/framework/web/filters/CFilterChain.php:134

   2538 run() /www/test.net/framework/web/CController.php:292

   2484 runActionWithFilters() /www/test.net/framework/web/CController.php:266

   2251 run() /www/test.net/framework/web/CWebApplication.php:276

   1799 translate() /www/test.net/application/libraries/Limesurvey_lang.php:118

   1786 load_tables() /www/test.net/application/third_party/php-gettext/gettext.php:254

   1447 runController() /www/test.net/framework/web/CWebApplication.php:135
复制代码
复制代码

    参数解释:

                sort:  对单词进行排序
                uniq -c:  显示唯一的行,并在每行行首加上本行在文件中出现的次数
                sort -k1,1nr:  按照第一个字段,数值排序,且为逆序
                head -10:  取前10行数据

  3)用strace跟踪进程

    a)利用nohup将strace转为后台执行,直到attach上的php-fpm进程死掉为止:

nohup strace -T -p 13167 > 13167-strace.log &

    参数说明:

       -c 统计每一系统调用的所执行的时间,次数和出错的次数等.
                -d 输出strace关于标准错误的调试信息.
                -f 跟踪由fork调用所产生的子进程.
                -o filename,则所有进程的跟踪结果输出到相应的filename
                -F 尝试跟踪vfork调用.在-f时,vfork不被跟踪.
                -h 输出简要的帮助信息.
                -i 输出系统调用的入口指针.
                -q 禁止输出关于脱离的消息.
                -r 打印出相对时间关于,,每一个系统调用.
                -t 在输出中的每一行前加上时间信息.
                -tt 在输出中的每一行前加上时间信息,微秒级.
                -ttt 微秒级输出,以秒了表示时间.
                -T 显示每一调用所耗的时间.
                -v 输出所有的系统调用.一些调用关于环境变量,状态,输入输出等调用由于使用频繁,默认不输出.
                -V 输出strace的版本信息.
                -x 以十六进制形式输出非标准字符串
                -xx 所有字符串以十六进制形式输出.
                -a column
                设置返回值的输出位置.默认为40.
                -e execve 只记录 execve 这类系统调用
                -p 主进程号

    b)用利用-c参数让strace帮助汇总,非常方便非常强大!

复制代码
复制代码
[root@b28-12 log]# strace -cp 9907

Process 9907 attached - interrupt to quit

Process 9907 detached

% time     seconds  usecs/call     calls    errors syscall

------ ----------- ----------- --------- --------- ----------------

56.61    0.016612           5      3121           read

11.11    0.003259           1      2517       715 stat

  8.04    0.002358           7       349           brk

  6.02    0.001767           1      1315           poll

  4.28    0.001255           6       228           recvfrom

  2.71    0.000796           1       671           open

  2.54    0.000745           0      2453           fcntl

  2.37    0.000696           1      1141           write

  1.69    0.000497           1       593        13 access

  1.37    0.000403           0      1816           lseek

  0.89    0.000262           1       451        22 sendto

  0.56    0.000163           1       276       208 lstat

  0.49    0.000145           0       384           getcwd

  0.31    0.000090           0      1222           fstat

  0.28    0.000082           0       173           munmap

  0.26    0.000077           0       174           mmap

  0.24    0.000069           2        41           socket

  0.23    0.000068           0       725           close

  0.00    0.000000           0        13           rt_sigaction

  0.00    0.000000           0        13           rt_sigprocmask

  0.00    0.000000           0         1           rt_sigreturn

  0.00    0.000000           0        78           setitimer

  0.00    0.000000           0        26        26 connect

  0.00    0.000000           0        15         2 accept

  0.00    0.000000           0        39           recvmsg

  0.00    0.000000           0        26           shutdown

  0.00    0.000000           0        13           bind

  0.00    0.000000           0        13           getsockname

  0.00    0.000000           0        65           setsockopt

  0.00    0.000000           0        13           getsockopt

  0.00    0.000000           0         8           getdents

  0.00    0.000000           0        26           chdir

  0.00    0.000000           0         1           futex

------ ----------- ----------- --------- --------- ----------------

100.00    0.029344                 18000       986 total
复制代码
复制代码

4.使用Opcode缓存(http://www.cnblogs.com/JohnABC/p/4531038.html)

5.对PHP性能进行监控

  常用的方法就是开启xdebug的性能监控功能,将xdebug输出结果通过WinCacheGrind软件分析。
  xdebug的安装和配合IDE调试的方法参见:Vim+XDebug调试PHP
 
  php.ini中配置的这几项是输出性能信息的:
xdebug.auto_trace = on
xdebug.auto_profile = on
xdebug.collect_params = on
xdebug.collect_return = on
xdebug.profiler_enable = on
xdebug.trace_output_dir = "/tmp"
xdebug.profiler_output_dir ="/tmp"
 
  这样XDebug会输出所有执行php函数的性能数据,但产生的文件也会比较大。可以关闭一些选项如collect_params、collect_return,
  来减少输出的数据量。或者关闭自动输出,通过在想要监控的函数首尾调用xdebug函数来监控指定的函数。
 
  输出的文件名类似cachegrind.out.1277560600和trace.3495983249.txt,可以拿到Windows平台下用WinCacheGrind进行图形化分析。

6.监测php-fpm线程状态

  nginx配置

location ~ ^/status$ {
    include fastcgi_params;
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_param SCRIPT_FILENAME $fastcgi_script_name;
}

  php-fpm配置

pm.status_path = /status

  这样的话通过http://域名/status就可以看到当前的php情况

  下面介绍每个参数的作用:
  pool:php-fpm池的名称,一般都是应该是www
  process manage:进程的管理方法,php-fpm支持三种管理方法,分别是static,dynamic和ondemand,一般情况下都是dynamic
  start time:php-fpm启动时候的时间,不管是restart或者reload都会更新这里的时间
  start since:php-fpm自启动起来经过的时间,默认为秒
  accepted conn:当前接收的连接数
  listen queue:在队列中等待连接的请求个数,如果这个数字为非0,那么最好增加进程的fpm个数
  max listen queue:从fpm启动以来,在队列中等待连接请求的最大值
  listen queue len:等待连接的套接字队列大小
  idle processes:空闲的进程个数
  active processes:活动的进程个数
  total processes:总共的进程个数
  max active processes:从fpm启动以来,活动进程的最大个数,如果这个值小于当前的max_children,可以调小此值
  max children reached:当pm尝试启动更多的进程,却因为max_children的限制,没有启动更多进程的次数。如果这个值非0,那么可以适当增加fpm的进程数
  slow requests:慢请求的次数,一般如果这个值未非0,那么可能会有慢的php进程,一般一个不好的mysql查询是最大的祸首。

7.开启php-fpm慢日志

  slowlog = /usr/local/php/log/php-fpm.log.slow

  request_slowlog_timeout = 5s

8.设置php-fpm单次请求最大执行时间,今天碰到一个问题,测试服务器php-fpm一直是被占满状态,后来发现是set_time_limit(0),file_get_content(),原因如下:

  比如file_get_contents(url)等函数,如果网站反应慢,会一直等在那儿不超时,php-fpm一直被占用。有一个参数 max_execution_time 可以设置 PHP 脚本的最大执行时间,但是,在 php-cgi(php-fpm) 中,该参数不会起效。真正能够控制 PHP 脚本最大执行时间的是 php-fpm.conf 配置文件中的以下参数。

  request_terminate_timeout = 10s

  默认值为 0 秒,也就是说,PHP 脚本会一直执行下去。这样,当所有的 php-cgi 进程都卡在 file_get_contents() 函数时,这台 Nginx+PHP 的 WebServer 已经无法再处理新的 PHP 请求了,Nginx 将给用户返回“502 Bad Gateway”。可以使用 request_terminate_timeout = 30s,但是如果发生 file_get_contents() 获取网页内容较慢的情况,这就意味着 150 个 php-cgi 进程,每秒钟只能处理 5 个请求,WebServer 同样很难避免“502 Bad Gateway”。php-cgi进程数不够用、php执行时间长、或者是php-cgi进程死掉,都会出现502错误。

  要做到彻底解决,只能让 PHP 程序员们改掉直接使用 file_get_contents("http://example.com/") 的习惯,而是稍微修改一下,加个超时时间,用以下方式来实现 HTTP GET 请求。要是觉得麻烦,可以自行将以下代码封装成一个函数。

复制代码
复制代码
<?php  
    $ctx = stream_context_create(array(  
       'http' => array(  
           'timeout' => 1 //设置一个超时时间,单位为秒  
           )  
       )  
    );  
    file_get_contents("http://example.com/", 0, $ctx);  
复制代码
复制代码

  当然,导致 php-cgi 进程 CPU 100% 的原因不只有这一种,那么,怎么确定是 file_get_contents() 函数导致的呢?

  首先,使用 top 命令查看 CPU 使用率较高的 php-cgi 进程。

复制代码
复制代码
top - 10:34:18 up 724 days, 21:01,  3 users,  load average: 17.86, 11.16, 7.69
Tasks: 561 total,  15 running, 546 sleeping,   0 stopped,   0 zombie
Cpu(s):  5.9%us,  4.2%sy,  0.0%ni, 89.4%id,  0.2%wa,  0.0%hi,  0.2%si,  0.0%st
Mem:   8100996k total,  4320108k used,  3780888k free,   772572k buffers
Swap:  8193108k total,    50776k used,  8142332k free,   412088k cached

  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND                                                                                                              
10747 www       18   0  360m  22m  12m R 100.6 0.3    0:02.60 php-cgi                                                                                                              
10709 www       16   0  359m  28m  17m R 96.8  0.4    0:11.34 php-cgi                                                                                                              
10745 www       18   0  360m  24m  14m R 94.8  0.3    0:39.51 php-cgi                                                                                                              
10707 www       18   0  360m  25m  14m S 77.4  0.3    0:33.48 php-cgi                                                                                                              
10782 www       20   0  360m  26m  15m R 75.5  0.3    0:10.93 php-cgi                                                                                                              
10708 www       25   0  360m  22m  12m R 69.7  0.3    0:45.16 php-cgi                                                                                                              
10683 www       25   0  362m  28m  15m R 54.2  0.4    0:32.65 php-cgi                                                                                                              
10711 www       25   0  360m  25m  15m R 52.2  0.3    0:44.25 php-cgi                                                                                                              
10688 www       25   0  359m  25m  15m R 38.7  0.3    0:10.44 php-cgi                                                                                                              
10719 www       25   0  360m  26m  16m R  7.7  0.3    0:40.59 php-cgi
复制代码
复制代码

  找其中一个 CPU 100% 的 php-cgi 进程的 PID,用以下命令跟踪一下:

strace -p 10747

  如果屏幕显示:

复制代码
复制代码
select(7, [6], [6], [], {15, 0})        = 1 (out [6], left {15, 0})
poll([{fd=6, events=POLLIN}], 1, 0)     = 0 (Timeout)
select(7, [6], [6], [], {15, 0})        = 1 (out [6], left {15, 0})
poll([{fd=6, events=POLLIN}], 1, 0)     = 0 (Timeout)
select(7, [6], [6], [], {15, 0})        = 1 (out [6], left {15, 0})
poll([{fd=6, events=POLLIN}], 1, 0)     = 0 (Timeout)
select(7, [6], [6], [], {15, 0})        = 1 (out [6], left {15, 0})
poll([{fd=6, events=POLLIN}], 1, 0)     = 0 (Timeout)
select(7, [6], [6], [], {15, 0})        = 1 (out [6], left {15, 0})
poll([{fd=6, events=POLLIN}], 1, 0)     = 0 (Timeout)
select(7, [6], [6], [], {15, 0})        = 1 (out [6], left {15, 0})
poll([{fd=6, events=POLLIN}], 1, 0)     = 0 (Timeout)
select(7, [6], [6], [], {15, 0})        = 1 (out [6], left {15, 0})
poll([{fd=6, events=POLLIN}], 1, 0)     = 0 (Timeout)
select(7, [6], [6], [], {15, 0})        = 1 (out [6], left {15, 0})
poll([{fd=6, events=POLLIN}], 1, 0)     = 0 (Timeout)
select(7, [6], [6], [], {15, 0})        = 1 (out [6], left {15, 0})
poll([{fd=6, events=POLLIN}], 1, 0)     = 0 (Timeout)
select(7, [6], [6], [], {15, 0})        = 1 (out [6], left {15, 0})
poll([{fd=6, events=POLLIN}], 1, 0)     = 0 (Timeout)
复制代码
复制代码

  那么,就可以确定是 file_get_contents() 导致的问题了。(参考:http://zyan.cc/tags/request_terminate_timeout/1/)

9.查看php-fpm启动时间(可以得出执行了多长时间)

ps -A -o pid,lstart,cmd |grep php-fpm

 

任务:配置多端口的php-fpm
1、进入配置目录,同php.ini目录[lighthouse@VM-4-12-centos etc]$ nl  php-fpm.conf     1  ;;;;;;;;;;;;;;;;;;;;;     2  ; FPM Configuration ;     3  ;;;;;;;;;;;;;;;;;;;;;
     4  ; All relative paths in this configuration file are relative to PHP's install     5  ; prefix (/www/server/php/72). This prefix can be dynamically changed by using the     6  ; '-p' argument from the command line.
     7  ;;;;;;;;;;;;;;;;;;     8  ; Global Options ;     9  ;;;;;;;;;;;;;;;;;;
    10  [global]    11  ; Pid file    12  ; Note: the default prefix is /www/server/php/72/var    13  ; Default Value: none    14  ;pid = run/php-fpm.pid
    15  ; Error log file    16  ; If it's set to "syslog", log is sent to syslogd instead of being written    17  ; into a local file.    18  ; Note: the default prefix is /www/server/php/72/var    19  ; Default Value: log/php-fpm.log    20  ;error_log = log/php-fpm.log    21  ; syslog_facility is used to specify what type of program is logging the    22  ; message. This lets syslogd specify that messages from different facilities    23  ; will be handled differently.    24  ; See syslog(3) for possible values (ex daemon equiv LOG_DAEMON)    25  ; Default Value: daemon    26  ;syslog.facility = daemon
    27  ; syslog_ident is prepended to every message. If you have multiple FPM    28  ; instances running on the same server, you can change the default value    29  ; which must suit common needs.    30  ; Default Value: php-fpm    31  ;syslog.ident = php-fpm
    32  ; Log level    33  ; Possible Values: alert, error, warning, notice, debug    34  ; Default Value: notice    35  ;log_level = notice
    36  ; If this number of child processes exit with SIGSEGV or SIGBUS within the time    37  ; interval set by emergency_restart_interval then FPM will restart. A value    38  ; of '0' means 'Off'.    39  ; Default Value: 0    40  ;emergency_restart_threshold = 0    41  ; Interval of time used by emergency_restart_interval to determine when    42  ; a graceful restart will be initiated.  This can be useful to work around    43  ; accidental corruptions in an accelerator's shared memory.    44  ; Available Units: s(econds), m(inutes), h(ours), or d(ays)    45  ; Default Unit: seconds    46  ; Default Value: 0    47  ;emergency_restart_interval = 0
    48  ; Time limit for child processes to wait for a reaction on signals from master.    49  ; Available units: s(econds), m(inutes), h(ours), or d(ays)    50  ; Default Unit: seconds    51  ; Default Value: 0    52  ;process_control_timeout = 0
    53  ; The maximum number of processes FPM will fork. This has been designed to control    54  ; the global number of processes when using dynamic PM within a lot of pools.    55  ; Use it with caution.    56  ; Note: A value of 0 indicates no limit    57  ; Default Value: 0    58  ; process.max = 128
    59  ; Specify the nice(2) priority to apply to the master process (only if set)    60  ; The value can vary from -19 (highest priority) to 20 (lowest priority)    61  ; Note: - It will only work if the FPM master process is launched as root    62  ;       - The pool process will inherit the master process priority    63  ;         unless specified otherwise    64  ; Default Value: no set    65  ; process.priority = -19
    66  ; Send FPM to background. Set to 'no' to keep FPM in foreground for debugging.    67  ; Default Value: yes    68  ;daemonize = yes

    69  ; Set open file descriptor rlimit for the master process.    70  ; Default Value: system defined value    71  ;rlimit_files = 1024
    72  ; Set max core size rlimit for the master process.    73  ; Possible Values: 'unlimited' or an integer greater or equal to 0    74  ; Default Value: system defined value    75  ;rlimit_core = 0
    76  ; Specify the event mechanism FPM will use. The following is available:    77  ; - select     (any POSIX os)    78  ; - poll       (any POSIX os)    79  ; - epoll      (linux >= 2.5.44)    80  ; - kqueue     (FreeBSD >= 4.1, OpenBSD >= 2.9, NetBSD >= 2.0)    81  ; - /dev/poll  (Solaris >= 7)    82  ; - port       (Solaris >= 10)    83  ; Default Value: not set (auto detection)    84  ;events.mechanism = epoll
    85  ; When FPM is built with systemd integration, specify the interval,    86  ; in seconds, between health report notification to systemd.    87  ; Set to 0 to disable.    88  ; Available Units: s(econds), m(inutes), h(ours)    89  ; Default Unit: seconds    90  ; Default value: 10    91  ;systemd_interval = 10
    92  ;;;;;;;;;;;;;;;;;;;;    93  ; Pool Definitions ;    94  ;;;;;;;;;;;;;;;;;;;;
    95  ; Multiple pools of child processes may be started with different listening    96  ; ports and different management options.  The name of the pool will be    97  ; used in logs and stats. There is no limitation on the number of pools which    98  ; FPM can handle. Your system will tell you anyway :)
    99  ; Include one or more files. If glob(3) exists, it is used to include a bunch of   100  ; files from a glob(3) pattern. This directive can be used everywhere in the   101  ; file.   102  ; Relative path can also be used. They will be prefixed by:   103  ;  - the global prefix if it's been set (-p argument)   104  ;  - /www/server/php/72 otherwise   105  include=/www/server/php/72/etc/php-fpm.d/*.conf注意最后一行105行[lighthouse@VM-4-12-centos etc]$ tree php-fpm.d/php-fpm.d/├── dzq.app.com-fpm.conf├── www.conf.default└── z.app.com-fpm.conf
[lighthouse@VM-4-12-centos php-fpm.d]$ nl dzq.app.com-fpm.conf     1  ; Start a new pool named 'www'.     2  ; the variable $pool can be used in any directive and will be replaced by the     3  ; pool name ('www' here)     4  [dzq.app.com]

    23  ; The address on which to accept FastCGI requests.    24  ; Valid syntaxes are:    25  ;   'ip.add.re.ss:port'    - to listen on a TCP socket to a specific IPv4 address on    26  ;                            a specific port;    27  ;   '[ip:6:addr:ess]:port' - to listen on a TCP socket to a specific IPv6 address on    28  ;                            a specific port;    29  ;   'port'                 - to listen on a TCP socket to all addresses    30  ;                            (IPv6 and IPv4-mapped) on a specific port;    31  ;   '/path/to/unix/socket' - to listen on a unix socket.    32  ; Note: This value is mandatory.    33  listen = 127.0.0.1:19000
2、nginx不同端口,做相应的fastcgi_pass配置        location ~ \.php$ {            fastcgi_index index.php;            fastcgi_pass 127.0.0.1:19000;
            #    fastcgi_pass unix:/tmp/php-cgi-72.sock;            include fastcgi.conf;
            # 传递脚本文件请求的路径;            # SCRIPT_FILENAME变量是php-fpm可识别的脚本名称;对应的$fastcgi_script_name变量是Nginx定义的脚本名称. $document_root变量是Nginx配置的根目录即root 指定的路径.本文配置当中可理解为,document_root= /usr/share/nginx/wordpress            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;        }
3、运行结果[lighthouse@VM-4-12-centos php-fpm.d]$ ps -ef | grep fpmlightho+  9240  3349  0 00:57 pts/0    00:00:00 grep --color=auto fpmroot     32751     1  0 00:27 ?        00:00:00 php-fpm: master process (/www/server/php/72/etc/php-fpm.conf)www      32752 32751  0 00:27 ?        00:00:04 php-fpm: pool dzq.app.comwww      32753 32751  0 00:27 ?        00:00:04 php-fpm: pool dzq.app.comwww      32754 32751  0 00:27 ?        00:00:00 php-fpm: pool z.app.comwww      32755 32751  0 00:27 ?        00:00:00 php-fpm: pool z.app.com[lighthouse@VM-4-12-centos php-fpm.d]$





posted @ 2018-09-18 10:31  papering  阅读(1374)  评论(0编辑  收藏  举报