PHP 接口请求超时,一般分为 PHP 执行超时、Nginx/Apache 超时、FastCGI 超时、数据库超时、外部接口超时 五大类。
我给你一份 企业级完整排查流程 + 解决方案清单,可以直接用在生产环境。
一、先判断是哪一层超时
不同报错代表不同问题:
| 报错信息 | 说明 |
|---|---|
Maximum execution time exceeded | PHP执行超时 |
504 Gateway Time-out | Nginx/反向代理超时 |
upstream timed out | FastCGI 超时 |
502 Bad Gateway | PHP-FPM挂了或崩了 |
| 页面一直转圈无报错 | 可能数据库卡住 |
二、PHP 层超时排查
1️⃣ max_execution_time
php.ini
max_execution_time = 30
动态设置:
set_time_limit(0); // 永不超时
查看当前值:
phpinfo();
如果你用的是 CLI:
php -i | grep max_execution_time
2️⃣ memory_limit
有时不是时间超时,而是内存爆了:
memory_limit = 128M
临时修改:
ini_set('memory_limit','512M');
三、Nginx 超时配置
文件位置:
/etc/nginx/nginx.conf
或
/etc/nginx/conf.d/*.conf
关键参数:
proxy_connect_timeout 300;
proxy_send_timeout 300;
proxy_read_timeout 300;
send_timeout 300;
如果是 FastCGI:
fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
修改后重启:
nginx -t
systemctl restart nginx
四、PHP-FPM 超时
配置文件:
/etc/php/8.x/fpm/pool.d/www.conf
关键参数:
request_terminate_timeout = 300
默认是 0(不限制),但很多服务器被改过。
重启:
systemctl restart php8.x-fpm
五、数据库导致的假超时(最常见)
1️⃣ 慢SQL
执行:
SHOW PROCESSLIST;
查看是否有:
Sending data
Locked
Waiting for table metadata lock
开启慢查询日志:
slow_query_log = 1
long_query_time = 1
优化索引:
EXPLAIN SELECT ...
2️⃣ 死锁
SHOW ENGINE INNODB STATUS;
六、外部接口超时(第三方API)
如果你在调用外部接口:
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
很多人忘记设置超时时间,导致一直卡住。
建议:
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
七、排查步骤(标准流程)
按顺序执行:
- 看浏览器报错类型
- 查看 Nginx error.log
/var/log/nginx/error.log - 查看 PHP-FPM log
/var/log/php8.x-fpm.log - 查看 MySQL 进程
- 看服务器 CPU / 内存
八、高并发导致的超时
如果是接口并发大:
1️⃣ 查看 PHP-FPM 进程数
ps aux | grep php-fpm
2️⃣ 查看配置
pm.max_children
pm.start_servers
pm.max_spare_servers
如果 pm.max_children 太小,会排队。
建议:
pm.max_children = 50
九、真正的解决方案(架构级)
如果接口执行时间超过 5 秒,说明设计有问题。
推荐方案:
✅ 1. 异步队列(强烈推荐)
用:
- Redis + 队列
- RabbitMQ
- Swoole
流程:
用户请求 → 立即返回 → 后台慢慢执行
✅ 2. 缓存
使用:
- Redis
- Memcached
比如:
$data = $redis->get('api_cache');
if(!$data){
$data = heavy_query();
$redis->setex('api_cache',300,$data);
}
✅ 3. 分页查询
不要:
SELECT * FROM big_table;
要:
SELECT * FROM big_table LIMIT 20;
十、服务器性能排查命令
CPU:
top
htop
内存:
free -m
IO:
iostat -x 1
连接数:
netstat -an | grep :80 | wc -l
十一、典型真实案例分析
案例1:504
原因:
fastcgi_read_timeout 60
接口执行 65 秒 → Nginx 杀掉
解决:
fastcgi_read_timeout 300;
案例2:页面卡死无报错
原因:
数据库未加索引,查询 800万数据
解决:
添加索引 + 分页
案例3:高峰期超时
原因:
pm.max_children=5
解决:
调到 50
十二、终极排查思路
超时本质只有 3 种:
- 执行太慢
- 并发太高
- 配置太小
你只要判断是哪个维度就能解决。
如果你愿意,我可以给你
- 🔥 一份生产环境标准 Nginx + PHP-FPM 优化配置
- 🔥 一份高并发接口架构图
- 🔥 一份慢SQL优化实战教程
- 🔥 一套企业级接口性能优化方案
你现在的环境是:
- Nginx 还是 Apache?
- PHP 版本?
- 是接口偶发超时还是全部超时?
告诉我具体环境,我给你针对性解决方案。
发表回复