PHP-FPM占用过多内存导致服务器响应缓慢的问题求助
Hey there, let's figure out why your PHP-FPM is gobbling up most of your memory and swap, and get that server response speed back on track!
First, let's start with your current PHP-FPM config settings you shared:
pm = ondemand
pm.max_children = 250
pm.process_idle_timeout = 3600s;
pm.max_requests = 500
核心配置问题分析
pm.max_children = 250: This is way too high for almost any typical server setup. Even if each PHP-FPM process only uses a modest 50MB of RAM, 250 processes would eat up 12.5GB right away. If your server doesn't have that much available RAM, it'll start swapping data to disk—which is a huge performance killer, hence your slow responses.pm.process_idle_timeout = 3600s: An hour is an extremely long time to let idle processes hang around. These processes aren't doing anything useful, they're just sitting there wasting memory that could be used for active requests.pm = ondemand: To be clear, this mode is actually great for memory efficiency because it only spawns processes when there's a request. But your other settings are completely undermining its benefits.
具体优化建议
Calculate a realistic
pm.max_childrenvalue:
Use this simple formula to get a starting point:pm.max_children = (Total Available RAM - RAM used by other critical services (MySQL, Nginx, etc.)) / Average memory per PHP-FPM processFor example: If you have 4GB of RAM, MySQL uses 1GB, and each PHP-FPM process uses ~50MB, that gives you (3072MB / 50MB) ≈ 61. Start with a conservative number like 40-60, then monitor your server load and adjust up or down as needed.
Drastically lower
pm.process_idle_timeout:
Set this to a much shorter window, like30sor60s. This way, idle processes get cleaned up quickly instead of hogging memory for an hour. Update the line to:pm.process_idle_timeout = 30s;Keep
pm.max_requestsbut tweak if needed:
500 is a reasonable default—it restarts processes after 500 requests to prevent memory leaks from piling up. If you suspect your PHP code has memory leaks, you can even lower this to 200-300 to mitigate the issue faster.
额外排查 tips
- Check individual PHP-FPM process memory usage: Run
ps aux | grep php-fpmto see how much RAM each process is consuming. If any are using 100MB+, you might have bloated code—think unoptimized database queries, memory-heavy libraries, or unclosed connections that aren't being cleaned up. - Enable PHP-FPM slow log: This will help you catch slow scripts that are causing processes to hang and chew up more memory. Add these lines to your PHP-FPM pool config:
slowlog = /var/log/php-fpm/slow.log request_slowlog_timeout = 5s - If you can share your top output: Details like how many php-fpm processes are running, their %MEM usage, and overall server memory stats would let us refine these suggestions even more precisely!
备注:内容来源于stack exchange,提问作者Bhavik

