温馨提示×

ubuntu php-fpm如何优化

小樊
39
2026-09-07 11:09:39
栏目: 编程语言

在 Ubuntu 上优化 PHP-FPM,通常从 进程管理、资源限制、缓存、系统层面 几个方向入手。下面按实战角度给你一套常见且有效的优化方案。


一、选择合适的 PHP-FPM 进程管理模式

PHP-FPM 主要有三种模式(pm):

1. static(稳定型)

pm = static
pm.max_children = 50

✅ 适合:高并发、内存充足 ❌ 不适合:内存紧张


2. dynamic(最常用)

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

✅ 适合:大部分 Web 服务


3. ondemand(省内存)

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

✅ 适合:访问量低、内存小(如低配服务器)


二、关键参数优化(最重要)

1. pm.max_children 怎么算?

经验公式:

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

例如:

  • 服务器 4G 内存
  • 每个 PHP 进程约 40MB
  • Nginx + MySQL 预留 1G
(4096 - 1024) / 40 ≈ 76

➡ 设置 pm.max_children = 70


2. 请求超时控制

request_terminate_timeout = 30s
request_slowlog_timeout = 5s
slowlog = /var/log/php-fpm-slow.log

✅ 防止死循环拖垮服务器


三、PHP 本身优化

1. 启用 OPcache(非常重要)

sudo apt install php-opcache

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

opcache.enable=1
opcache.memory_consumption=128
opcache.max_accelerated_files=10000
opcache.revalidate_freq=60
opcache.validate_timestamps=0  ; 生产环境建议关闭

2. 关闭不必要功能

expose_php = Off
display_errors = Off
log_errors = On

四、系统层面优化(Ubuntu)

1. 文件描述符限制

ulimit -n 65535

/etc/security/limits.conf

* soft nofile 65535
* hard nofile 65535

2. 调整 TCP / 网络

sysctl -w net.core.somaxconn=65535
sysctl -w net.ipv4.tcp_tw_reuse=1

五、Nginx + PHP-FPM 配合优化

Nginx 示例

fastcgi_buffer_size 128k;
fastcgi_buffers 4 256k;
fastcgi_busy_buffers_size 256k;
fastcgi_read_timeout 30s;

六、监控 PHP-FPM 状态(强烈推荐)

开启 status

pm.status_path = /status

Nginx:

location /status {
    fastcgi_pass unix:/run/php/php-fpm.sock;
    include fastcgi_params;
    allow 127.0.0.1;
    deny all;
}

查看:

curl 127.0.0.1/status

七、常见优化误区 ❌

  • max_children 越大越好(会 OOM)
  • 开 validate_timestamps=1 影响性能
  • 忽略 slow log
  • 用 root 跑 PHP-FPM

八、推荐生产配置示例(2核4G)

pm = dynamic
pm.max_children = 60
pm.start_servers = 10
pm.min_spare_servers = 5
pm.max_spare_servers = 20
request_terminate_timeout = 30s
request_slowlog_timeout = 5s

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

  • Ubuntu 版本
  • PHP 版本
  • 服务器配置(CPU / 内存)
  • 网站类型(WordPress / API / 商城)

我可以直接给你 一套可直接用的配置。

0 踩