Home  >  Article  >  Operation and Maintenance  >  How to optimize php+php-fom+nginx configuration parameters

How to optimize php+php-fom+nginx configuration parameters

WBOY
WBOYforward
2023-06-03 20:04:50893browse

How to optimize php+php-fom+nginx configuration parameters

1. Foreword

For a new server, installing the LNMP environment is only the first step. The second step is of course to modify the default Configure parameters to make these programs easier to use and improve performance. This article mainly talks about the configuration parameters of php php-fpm nginx. The machine is a server with 4GB memory. The relevant configurations are configured according to the server with 4GB memory. of.

1. Mysql configuration parameters:

Mysql configuration parameter tuning (8GB memory and 64GB memory)
Mysql configuration file composition and specific configuration demo

2. Note

The configuration items listed below have an impact on performance or must be configured. Configuration items not listed are default settings. There are many configuration parameters for these three programs. Our server cannot use too complicated configurations at the beginning. The following configuration is mainly to maximize the high concurrency and improve the performance of the program.

php and php-fpm are both version 5.6. (Everything is for compatibility with old projects, hard work)

2. PHP parameter configuration and explanation

1. Basic settings of phpini

(1)safe_mode  这份的配置采用默认的
(2)disable_functions  在默认的基础上,加上eval()函数
(3)expose_php = off
(4)register_globals和magic_quotes_gpc参数都在php5.4.0后被移除了
(5)错误提示以及日志部分采用默认的就行,现在大部分使用的都是框架,
查看框架的错误日志更方便

These few This parameter is often mentioned on the Internet, but we do not have to follow their configuration here. After all, it has been a long time, and many bug or performance issues have been fixed.

2. PHP parameter setting

(1) max_execution_time = 300

The maximum time for the script to run. If the specified time is exceeded, the script will automatically kill For this request, in order to be able to upload large files, this value is set larger. If this value is too small, it will also cause a program 502 error.

(2)memory_limit = 128M

Maximum memory used by each script

(3)max_inpit_time = 300

The maximum time each script waits for input data

(4) upload_max_filesize = 20M

The maximum allowed size of uploaded files

(5)allow_url_fopen = off

Do not open the remote address

(6)post_max_size = 20M
postThe size of the upload must be >=upload_max_filesize

(7);cgi.fix_pathinfo=1
It is turned on by default, currently the higher version php has avoided this vulnerability. The default value of security.limit_extensions of php-fpm has long been .php. So we can just use the default value for this parameter.
Reference: php fpm setting item cgi.fix_pathinfo=1 The vulnerability no longer appears

About php.ini, these are the parameters to be set, mainly to increase the running time of the program , increasing the upload file size, etc., can facilitate our usual php development.

3. php-fpm settings

1. Set the number of child processes and increase the amount of concurrency

log_level = notice		//notice级别的日志,默认的
rlimit_files = 4048		//调整最大打开文件数量
pm选用动态变化的dynamic

process.max = 150		// 最大子进程,设置成和max_children一样就行
pm = dynamic
pm.max_children = 150	//最大子进程,假如一个进程30M,4G内存的话最大为:4048/30 = 135,取150
pm.start_servers = 20
pm.min_spare_servers = 6
pm.max_spare_serveres = 30   
//计算公式是:min_spare_servers ≤ start_servers ≤ max_spare_servers ≤ max_children

Many people suggest that if your memory is relatively large, then Set static pm = static. At this time, only the max_children parameter works. Initially, there are max_children processes, and there is just one The php-fpm process only occupies about 3M of memory. Our 4GB machine is calculated as a process of 20M, and max_children can be set. It is 200 or 150. If it is a dedicated php server, it is recommended to set it to static for the best performance.

It is also possible if it is set to dynamic. In this case, programs such as start_servers will work, and new processes will continue to be added as the business increases, but the maximum number of processes cannot exceed max_children's. The blogger considered that the machine has small memory and also runs mysql, redis, etc., so he chose the dynamic one, so that there will not be a lot of pressure at the beginning, etc. As the number of visits increases, it may be modified to static.

2. Prevent frequent 502 errors

(1) process_control_timeout = 20

php-fpmAllocate to child process The time interval of

(2) request_terminate_timeout = 320s

means waiting for 320 seconds before ending those php# that have not ended automatically. ##Script to release occupied resources. Setting 320s is mainly because the program running time of php is 300s, so for php-fpm, this value should be greater than phpThe running time specified by the script (because the running of the php script may also include the mysql service or some other services, this parameter is to kill this Process, including pure php scripts and other services).

(3) Automatic restart setting

#表示在emergency_restart_interval所设值内出现SIGSEGV或者SIGBUS错误的php-cgi进程数如果
#超过emergency_restart_threshold个php-fpm就会优雅重启。这两个选项一般保持默认值

emergency_restart_threshold = 30
emergency_restart_interval = 60s	//一分钟内出现30次上述信号即重启php-fpm

(4)pm.max_requests = 1000

for each child process The maximum number of requested services. If this value is exceeded, the child process will be automatically restarted.

比如max_requests这个参数,如果设置很大的话,那这个子进程要运行很多次才会重启,假如这个请求发生了错误或者内存泄漏,那么这个值设置很大是不合适的。但如果请求没有问题,这个值设置小的话就会频繁的重启,这样也会碰到不少502的问题,所以要仁者见仁,智者见智的设置了,这里初始化设置1000,如果测试没有内存泄漏等问题,可以再大一些。

3、php-fpm中的慢日志设置

mysql中有慢日志这个概念,可以记录查询速度比较慢的sql,同样的,php-fpm也可以开启慢日志,记录执行速度比较慢的php请求,方便我们后续的调试和优化。

(1)慢日志的主要参数

request_slowlog_timeout : 默认是注释的,打开注释,设置为1,代表请求超过1s,就会记录这个脚本到慢日志文件中。也可以的更大,按照需求来。
slowlog  : 默认也是注释的,可以打开注释使用默认的慢日志路径,也可以自定义路径。

这里开启慢日志,如下:

request_slowlog_timeout = 2   # 记录超过2s的请求
slowlog = /var/log/php-fpm/www-slow.log	#慢日志路径
(2)利用sort/uniq命令分析汇总php-fpm慢日志:
grep -v “^$” www.log.slow.tmp | cut -d ” ” -f 3,2 | sort | uniq -c | sort -k1,1nr | head -n 50

参数解释:

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

4、php-fpm中的backlog是干啥的?

如果worker进程不够用,master进程会prefork更多进程,如果prefork达到了pm.max_children上限,worker进程又全都繁忙,这时master进程会把请求挂起到连接队列backlog里,而backlog默认值是511,除了加大pm.max_children,调整backlog也是有必要的。

也就说这个backlog是在优化高并发的时候必须要设置的,这个值的大小和fpmqps也有关。backlog太大,fpm处理不过来照样会报错504(超时)。这个对于目前的机器来说,我设置的max_children = 150,然而backlog的默认值是511,所以在短期内是完全够用的,不过也可以在php-fpm.conf里面显式的制定backlog的值,比如制定:listen.backlog = 1024 #2的n次幂

参考:

PHP参数调优
nginx报错502:connect() to unix:/var/run/php5-fpm.sock failed (2: No such file or directory)
php-fpm进程数管理
关于PHP-FPM的backlog的默认值
PHP-FPM中backlog参数变更的一些思考
PHP-fpm

四、nginx配置参数调优

1、nginx中的一些层级关系

一般打开nginx配置文件,会发现有httpserver,location等,那么他们的层级关系是什么样的呢?

答案是: 一个http里面可以有多个server,一个server里面可以有多个location

我们配置的时候,各个server共用的部分可以配置在http模块里面。每个server自己特有的一些部分,按照各自的需求配置在server模块里面。同样的,对于location是分的更细的,按照每个server的每个location需求来配置。

其次是如果在conf.d文件夹下有其他的配置文件,那么我们的nginx.conf就是公用的配置文件了,一些公用的部分都可以配置在nginx.conf文件中,各个站点特殊的配置就放在conf.d文件下。

参考:
nginx短篇(4):模块、配置指令、块之间的关系

2、nginx.conf 实例及解释

user www-data;
worker_processes auto; #自动检测CPU的核数
worker_rlimit_nofile 65535;  #worker进程的最大打开文件数限制
error_log   /var/log/nginx/error.log;
include /etc/nginx/modules-enabled/*.conf;
pid /run/nginx.pid;

events {
    worker_connections  10240;  #子进程最大连接数,总连接数:worker_processes * worker_connections
    use epoll; #使用epoll模型
}

http {
    include       mime.types; # #文件扩展名与文件类型映射表
    default_type  application/octet-stream;  #这个类型会让浏览器认为响应是普通的文件流,并提示用户下载文件

        #记录都有哪些变量可以记录到log_format
        log_format  main  '$remote_addr $host $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_accept_language" "$request_time" '
                      '"$upstream_response_time" "$upstream_addr" "$upstream_status" "$http_x_real_ip" "$proxy_add_x_forwarded_for"';

    sendfile        on;  #立即将数据从磁盘读到OS缓存
    tcp_nopush      on;  #告诉nginx在一个数据包里发送所有头文件
    tcp_nodelay     on;  # 告诉nginx不要缓存数据,而是一段一段的发送
    keepalive_timeout  30; #服务器将在这个超时时间过后关闭链接
    types_hash_max_size 2014;

    #resolver xxx;  #用于解析上游服务器名称的名称服务器配置到地址中
    gzip_static on;
    gzip  on;
    gzip_http_version 1.1;
    gzip_vary off;
    gzip_comp_level 4;  #数据的压缩等级,9是最慢但是压缩比最大的
    gzip_proxied off;
    gzip_buffers 16 8k;
    gzip_disable "MSIE [1-6]\.(?!.*SV1)";
    #设置需要压缩的数据格式
    gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/hero-res;

    client_max_body_size 20m;  #设置网页上传文件的最大值,和php.ini中的上传设置保持一致
    server_names_hash_max_size 2048;  #保存服务器名字的hash表

    include /etc/nginx/client.conf;
    include /etc/nginx/conf.d/*.conf;
}

(1)worker_rlimit_nofile

更改worker进程的最大打开文件数限制。

查看当前进程可以打开的文件数:

ulimit-n			
//结果:65535

查看当前系统可以打开的最大文件数:

ljf@hx:cat /proc/sys/fs/file-max
813544

(2)log_format中的内容

参考官网:https://nginx.org/en/docs/http/ngx_http_core_module.html#var_status

remote_addr:对应客户端的地址
remote_user:是请求客户端请求认证的用户名,如果没有开启认证模块的话是值为空。
time_local:表示nginx服务器时间
request:表示request请求头的行
status:表示response的返回状态
body_bytes_sent:表示从服务端返回给客户端的body数据大小
http_referer:表示请求的上一级页面
http_user_agent:表示agent信息
http_x_forwarded_for:会记录每一级请求中信息

(3)gzip压缩相关解释

参考:https://www.jb51.net/article/95041.htm

(4)client_max_body_size设置

这个参数规定客户端上传的body的最大值,和php.ini中的最大上传数保持一致,不然的话,就算php.ini设置上传的最大文件是1G,如果nginx
不设置这个参数的话,那么上传一样会报错的。

3、对于conf.d文件夹中的配置

(1)配置实例代码

server{
      listen IP:80;
    server_name xxx;
    access_log  /var/log/nginx/access.log;  #access日志

    fastcgi_intercept_errors on; #支持nginx404重定向

    index index.php index.html  index.htm;

    root /product/ucool/production/manage/htdocs/backend/web/;

        send_timeout 15;
        #客户端与服务器建立连接后发送request body的超时时间(小于keepalive_timeout)
        client_body_timeout 20;
        #客户端向服务器发送一个完整的request header的超时时间(小于keepalive_timeout)
        client_header_timeout 20;
        fastcgi_connect_timeout         300;    #指定连接到后端FastCGI的超时时间
        fastcgi_send_timeout            300;    #指定向FastCGI传送请求的超时时间
        fastcgi_read_timeout            300;    #指定接收FastCGI应答的超时时间
        fastcgi_buffer_size 64k;               #指定读取FastCGI应答第一部分需要用多大的缓冲区
        fastcgi_buffers 4 64k;                 #定本地需要用多少和多大的缓冲区来缓冲FastCGI的应答请求


      location ~* ^.+\.(git|svn|sql|bak|old|rar|tgz|7z|bz2|tar|idea)$ {
        return 404;
      }
      location ~ \.php$ {
                fastcgi_pass unix:/var/run/php/php5.6-fpm.sock;
                fastcgi_index index.php;
                fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
                include fastcgi_params;
                proxy_set_header Host $host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      }
        location ~ /\.git { deny all; }
}

(2)主要是fastcgi的一些配置

这里不考虑负载均衡和反向代理,关于fastcgi的优化可以参考:

https://www.jb51.net/article/145222.htm

(3)关于send_timeout

    send_timeout 15;
    #客户端与服务器建立连接后发送request body的超时时间(小于keepalive_timeout)
    client_body_timeout 20;
    #客户端向服务器发送一个完整的request header的超时时间(小于keepalive_timeout)
    client_header_timeout 20;

这几个参数最好是再小一些,包括keepalive_timeout,小一些的话,能处理更多的有效请求,有利于提升nginx的处理性能,大佬们的设置如下:

client_body_timeout 12;
client_header_timeout 12;
keepalive_timeout 15;
send_timeout 10;

4、保存编辑之后检查配置文件的正确性

(1)检查配置文件是否正确
ljf@hx:/etc/nginx$ sudo nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

返回successful并且没有报错信息的话,说明配置文件里面的语法是没问题的,如果报错了那就是语法出错了,导致配置无法正常读取。

(2)检查子级配置文件是否正确
nginx -t -c /etc/nginx/conf.d/xxx.conf

例如:

ljf@hx:/etc/nginx$ sudo nginx -t -c /etc/nginx/conf.d/api.conf
nginx: [emerg] "server" directive is not allowed here in /etc/nginx/conf.d/api.conf:1
nginx: configuration file /etc/nginx/conf.d/api.conf test failed

很明显配置文件是错的。

五、影响程序超时的参数

php.ini中有max_execution_time 参数。
php-fpm中有request_terminate_timeout参数
nginx.conf中有 fastcgi_connect_timeout 等参数。

1、关于php和php-fpm超时时间的设置

首先是max_execution_time 这个值限定了脚本的最大执行时间,但是仅限于php脚本,对于脚本中的流操作和数据库操作等耗费的时间是不算进去的。而php-fpmrequest_terminate_timeout 代表单个请求的超时中止时间,并不会受其他脚本影响,定义10s结束,那么10s就准时结束该php脚本的运行。所以配置超时时间的时候,request_terminate_timeout 可以比max_execution_time  稍微大一些。

还有一种说法,在服务器正常运行的时候,php-fpm.conf中的request_terminate_timeout 会覆盖php.ini中的max_execution_time,所以request_terminate_timeout 的值更代表我们对于脚本执行时间的预期。如果服务器性能足够好,可以设置request_terminate_timeout = 0代表永不超时。

当程序运行时间大于规定的参数的时候,php-fpm会终止该php子进程。

2、nginx中的超时设置

nginxfastcgi_connect_timeout 操作影响的是ningx的超时,一般来说,如果是php或者php-fpm超时,那么报错502 Bad Gateway(网关错误)  。如果是nginx超时的话,报错是:504 Gateway Time-out (网关超时) ,到时候我们可以根据这个报错信息来定位问题。一般来说,为防止频繁的出现超时错误,设置fastcgi_connect_timeout 相关时间为300s是合适的。

假如设置fastcgi_read_timeout=10test.php执行时间100秒,则10秒后webserver会关闭和PHP的连接。也就是说当程序运行时间大于规定的参数的时候,webserver会关闭和PHP的连接,出现超时错误。所以这个fastcgi的超时时间最好是和php-fpm中的request_terminate_timeout 保持一致。

3、nginx中的keepalive_timeout

keepalive_timeout参数是一个请求完成之后还要保持连接多久,不是请求时间多久,目的是保持长连接,减少创建连接过程给系统带来的性能损耗,类似于线程池,数据库连接池。

The above is the detailed content of How to optimize php+php-fom+nginx configuration parameters. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete