温馨提示×

Ubuntu PHP-FPM如何加速

小樊
36
2026-07-28 01:13:19
栏目: 编程语言

在 Ubuntu 上加速 PHP-FPM,通常从 配置优化、系统资源、OPcache、上下游(Nginx/Apache) 几个层面入手。下面按“最有效果 → 进阶”的顺序给你一套实战方案。


一、核心:优化 PHP-FPM 配置(最关键)

1️⃣ 找到 PHP-FPM 配置文件

# 查看 PHP 版本
php -v

# 示例(PHP 8.2)
/etc/php/8.2/fpm/pool.d/www.conf

2️⃣ 调整进程管理模式(重点)

推荐 pm = dynamic(适合大多数网站)

pm = dynamic
pm.max_children = 50
pm.start_servers = 10
pm.min_spare_servers = 5
pm.max_spare_servers = 20

如何计算 pm.max_children

max_children ≈ 可用内存 / 每个 PHP 进程内存

示例:

  • 服务器内存:4GB
  • 每个 PHP 进程:50MB
  • 最大子进程 ≈ 4096 / 50 ≈ 80

⚠️ 不要设置过大,否则会 OOM


3️⃣ 高并发站点(API / 秒杀)

可尝试:

pm = ondemand
pm.max_children = 100
pm.process_idle_timeout = 10s

二、开启并优化 OPcache(提速 2~5 倍)

1️⃣ 安装 OPcache(一般已内置)

php -m | grep opcache

2️⃣ 配置 OPcache

编辑:

/etc/php/8.2/fpm/conf.d/10-opcache.ini

推荐配置:

opcache.enable=1
opcache.memory_consumption=256
opcache.interned_strings_buffer=32
opcache.max_accelerated_files=50000
opcache.validate_timestamps=0   ; 生产环境关闭
opcache.revalidate_freq=0
opcache.jit_buffer_size=128M
opcache.jit=1255

生产环境一定要关闭 validate_timestamps


三、优化 PHP 本身

1️⃣ 升级 PHP 版本

PHP 8.x 比 7.x 快 20%~40%

sudo apt update
sudo apt install php8.2-fpm

2️⃣ 禁用不必要扩展

php -m

注释掉不用的:

;extension=ftp
;extension=ldap

四、Nginx / Apache 优化(非常重要)

✅ Nginx + PHP-FPM 推荐配置

nginx 站点配置

location ~ \.php$ {
    include fastcgi_params;
    fastcgi_pass unix:/run/php/php8.2-fpm.sock;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

    fastcgi_buffers 16 16k;
    fastcgi_buffer_size 32k;
    fastcgi_read_timeout 120;
}

五、系统层面加速

1️⃣ 文件描述符限制

ulimit -n

修改:

/etc/security/limits.conf
* soft nofile 65535
* hard nofile 65535

2️⃣ TCP / 内核参数(高并发)

/etc/sysctl.conf
net.core.somaxconn = 65535
net.ipv4.tcp_tw_reuse = 1
sudo sysctl -p

六、数据库 & 应用层(常被忽略)

✅ 数据库

  • 使用 MySQL 慢查询日志
  • 加索引
  • 使用 Redis 缓存查询结果

✅ 应用层

  • 减少 file_exists() / glob()
  • 避免每次请求都解析 .env
  • 使用 Laravel Octane / Swoole(如适用)

七、快速检查清单 ✅

✅ PHP-FPM pm 配置合理
✅ OPcache 已开启并优化
✅ PHP ≥ 8.1
✅ Nginx 使用 Unix Socket
✅ 没有内存溢出
✅ 使用 Redis / 缓存


八、一键诊断命令

# PHP-FPM 状态
systemctl status php8.2-fpm

# 查看进程数
ps aux | grep php-fpm | wc -l

# 内存占用
top -p $(pgrep php-fpm | head -1)

如果你愿意,可以告诉我:

  • ✅ Ubuntu 版本
  • ✅ PHP 版本
  • ✅ 网站类型(WordPress / Laravel / API)
  • ✅ 并发量 / 内存

我可以 直接给你一套最优配置

0