ubuntu

Ubuntu下php-fpm如何配置缓存策略

小樊
40
2026-01-07 00:29:12
栏目: 编程语言

在 Ubuntu 下,配置 PHP-FPM 缓存策略通常涉及到两个主要方面:PHP 代码的 OpCode 缓存和 PHP-FPM 的进程管理。以下是一些常见的配置选项和建议:

1. OpCode 缓存

OpCode 缓存可以显著提高 PHP 脚本的执行速度。常用的 OpCode 缓存扩展有 OPcache 和 APCu。

安装 OPcache

OPcache 是 PHP 7.2 及以上版本的内置扩展,无需额外安装。你可以在 php.ini 文件中启用它:

[opcache]
zend_extension=opcache.so
opcache.enable=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000
opcache.revalidate_freq=60
opcache.fast_shutdown=1

配置 OPcache

2. PHP-FPM 进程管理

PHP-FPM 的进程管理可以通过 www.conf 文件进行配置。以下是一些关键配置项:

; Start a new pool named 'www'.
[www]

; The address on which to accept FastCGI requests.
; Valid syntaxes are:
;   'ip.add.re.ss:port'    - to listen on a TCP socket to a specific IPv4 address on
;                            a specific port;
;   '[ip:6:addr:ess]:port' - to listen on a TCP socket to a specific IPv6 address on
;                            a specific port;
;   'unix:/path/to/unix/socket' - to listen on a unix socket.
; Note: This value is mandatory.
listen = /run/php/php7.4-fpm.sock

; Set listen(2) backlog.
listen.backlog = -1

; Set permissions for unix socket, if one is used. In Linux, read/write
; permissions must be set in order to allow inter-process communication.
; Security note: Use "chmod 660 /path/to/unix/socket" to keep PHP-FPM
;     and web server (e.g. nginx) separate.
; Unix user/group of processes
; Note: The user is mandatory. If the group is not set, the default user's group
;       will be used.
user = www-data
group = www-data

; The URL handler will look for this file for each request started with the @ symbol.
; It is used to launch applications or scripts without specifying the full path.
; It is recommended to use absolute paths in this file for security reasons.
; Note: If you are using subrequests, make sure that the path to the file is relative
; to the location of the subrequest. Otherwise, you may provide an absolute path to it.
; For example:
;   ; http://example.com/app.php/foo
;   ; http://example.com/app.php/bar?foo=bar
; php_value[error_log] = /var/log/fpm-php-www.log
; php_admin_value[error_log] = /var/log/fpm-php-www-admin.log
; php_admin_flag[log_errors] = on
; See default values in php-fpm.d/www.conf.default

; When PHP-FPM is running as a daemon, it is not necessary to specify the user and group
; because the daemon process will automatically use the appropriate system user and group.
; If you need to change the daemon user/group, uncomment this line:
;   ;user = daemon
;   ;group = daemon

; The directory in which mpm will store PID files.
; Default: /var/run/php
; pm = dynamic
; pm.max_children = 5
; pm.start_servers = 2
; pm.min_spare_servers = 1
; pm.max_spare_servers = 3

关键配置项解释

3. 其他优化建议

通过以上配置,你可以显著提高 PHP-FPM 在 Ubuntu 系统上的性能和稳定性。记得在修改配置文件后重启 PHP-FPM 服务:

sudo systemctl restart php7.4-fpm

根据你的 PHP 版本,替换 php7.4-fpm 为相应的版本号。

0
看了该问题的人还看了