优化Ubuntu上PHP脚本执行速度的系统性方案
OPcache是PHP官方推出的字节码缓存扩展,能将编译后的PHP脚本存储在内存中,避免重复编译,显著提升脚本执行效率。
php-opcache(根据PHP版本调整,如php8.2-opcache)。php.ini(路径可通过php --ini获取),添加/修改以下关键参数:zend_extension=opcache.so
opcache.enable=1
opcache.memory_consumption=128 # 缓存内存大小(MB),根据服务器内存调整
opcache.max_accelerated_files=10000 # 缓存文件数量上限
opcache.revalidate_freq=60 # 文件修改后重新验证间隔(秒)
opcache.fast_shutdown=1 # 快速关闭机制,减少内存释放时间
sudo systemctl restart php8.2-fpm。PHP-FPM(FastCGI Process Manager)比传统mod_php更适合高并发场景,合理的进程配置能有效利用服务器资源。
sudo apt install php-fpm安装。/etc/php/8.2/fpm/pool.d/www.conf(版本替换为实际PHP版本),调整以下参数:pm = dynamic # 动态进程管理模式(适合大多数场景)
pm.max_children = 50 # 最大子进程数(根据服务器内存计算:总内存/单个进程内存,如1GB内存约设20-30)
pm.start_servers = 10 # 启动时的子进程数(建议为pm.max_children的20%-30%)
pm.min_spare_servers = 5 # 最小空闲进程数(避免频繁创建进程)
pm.max_spare_servers = 20 # 最大空闲进程数(避免资源浪费)
pm.max_requests = 500 # 单个子进程处理的最大请求数(防止内存泄漏)
sudo systemctl restart php8.2-fpm。调整php.ini中的关键参数,避免资源浪费和脚本超时。
memory_limit = 256M # 单个脚本最大内存(根据应用需求调整,避免过大)
max_execution_time = 30 # 脚本最大执行时间(秒,避免长时间阻塞)
post_max_size = 32M # POST请求最大数据量(根据表单需求调整)
upload_max_filesize = 32M # 上传文件最大大小(与post_max_size一致)
disable_functions = exec,passthru,shell_exec # 禁用危险函数(提升安全性)
display_errors = Off(生产环境关闭错误显示)、expose_php = Off(隐藏PHP版本信息)。Nginx相比Apache在高并发场景下性能更优,且资源占用更低,适合作为PHP的前端服务器。
sudo apt install nginx。/etc/nginx/sites-available/default),添加以下内容:location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php8.2-fpm.sock; # 使用Unix Socket(性能优于TCP)
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
sudo nginx -t(测试配置正确性),sudo systemctl restart nginx。数据库查询是PHP应用的常见性能瓶颈,使用Redis或Memcached缓存频繁访问的数据,能显著减少数据库查询次数。
sudo apt install php-redis redis-server(php-redis为Redis PHP扩展)。$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$key = 'user_data_' . $userId;
if ($redis->exists($key)) {
$userData = $redis->get($key);
} else {
$userData = $db->query("SELECT * FROM users WHERE id = $userId")->fetch();
$redis->setex($key, 3600, serialize($userData)); // 缓存1小时
}
sudo systemctl restart redis-server。通过工具定位性能瓶颈,针对性优化代码。
sudo apt install php-xdebug),配置php.ini:zend_extension=xdebug.so
xdebug.mode=profile
xdebug.output_dir=/tmp/profiler
运行脚本后,使用Webgrind或KCacheGrind分析生成的cachegrind.out文件,找出执行时间最长的函数。建立监控体系,实时掌握系统状态,及时发现并解决问题。
htop(实时CPU/内存)、vmstat(系统整体性能)、iostat(磁盘I/O)等工具监控服务器状态。slowlog = /var/log/php-fpm/slow.log
request_slowlog_timeout = 5s # 超过5秒的请求记录到慢日志
使用grep或pt-query-digest分析慢日志,找出问题脚本。