PHP-FPM在出现502时的一种解决方案


买了一个阿里云的服务器,最低配置。装上wordpress、phpmyadmin。跑起来发现,偶尔就会有502出现,查找原因,是由于php-fpm在执行的时候申请内存失败了。。。

那么如何在有限的内存下,保证不会502呢?

搜了下php-fpm的相关配置,其中几项很有用的如下:

; Choose how the process manager will control the number of child processes.
; Possible Values:
; static – a fixed number (pm.max_children) of child processes;
; dynamic – the number of child processes are set dynamically based on the
; following directives:
; pm.max_children – the maximum number of children that can
; be alive at the same time.
; pm.start_servers – the number of children created on startup.
; pm.min_spare_servers – the minimum number of children in ‘idle’
; state (waiting to process). If the number
; of ‘idle’ processes is less than this
; number then some children will be created.
; pm.max_spare_servers – the maximum number of children in ‘idle’
; state (waiting to process). If the number
; of ‘idle’ processes is greater than this
; number then some children will be killed.
; Note: This value is mandatory.
pm = dynamic

; The number of child processes to be created when pm is set to ‘static’ and the
; maximum number of child processes to be created when pm is set to ‘dynamic’.
; This value sets the limit on the number of simultaneous requests that will be
; served. Equivalent to the ApacheMaxClients directive with mpm_prefork.
; Equivalent to the PHP_FCGI_CHILDREN environment variable in the original PHP
; CGI.
; Note: Used when pm is set to either ‘static’ or ‘dynamic’
; Note: This value is mandatory.
pm.max_children = 10

; The number of child processes created on startup.
; Note: Used only when pm is set to ‘dynamic’
; Default Value: min_spare_servers + (max_spare_servers – min_spare_servers) / 2
pm.start_servers = 5

; The desired minimum number of idle server processes.
; Note: Used only when pm is set to ‘dynamic’
; Note: Mandatory when pm is set to ‘dynamic’
pm.min_spare_servers = 2

; The desired maximum number of idle server processes.
; Note: Used only when pm is set to ‘dynamic’
; Note: Mandatory when pm is set to ‘dynamic’
pm.max_spare_servers = 10

; The number of requests each child process should execute before respawning.
; This can be useful to work around memory leaks in 3rd party libraries. For
; endless request processing specify ‘0’. Equivalent to PHP_FCGI_MAX_REQUESTS.
; Default Value: 0
pm.max_requests = 20

这是从php-fpm配置中复制出来的,意思也都很好理解。说说数值的修改吧。

开始发现内存不足的时候,查看进程列表,发现很多php-fpm进程。每个占用6%-8%的内存(30M-40M)。

由于内存总数也就512M,无限制的php-fpm进程必然会导致内存不足。所以,修改pm.max_children = 10,最多产生10个php-fpm进程。使用内存最多在400MB左右。

实际运行的时候会发现,新开启的php-fpm进程会占用相当少的内存(0.9% 4.6M)。而且php-fpm自身就能平滑重启,设置pm.max_requests = 20。单个php-fpm进行处理20个请求后重启。

由于内存紧张,空闲的php-fpm只要能满足小量请求就可以了,所以pm.min_spare_servers = 2,只运行两个空闲的php-fpm进行存在。(很多时候yum install都会由于内存不足被killed。。。泪啊。。。

修改了以上这些配置后,再没出现过502错误~~


发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注