在 Ubuntu 上优化 Laravel 性能,通常可以从 系统层面、PHP 层面、Laravel 自身、数据库、缓存与运维 几个维度来做。下面是一套比较实用、可落地的优化方案。
mod_phpsudo apt install nginx php-fpm
编辑:
/etc/php/8.x/fpm/pool.d/www.conf
关键参数(示例,按服务器配置调整):
pm = dynamic
pm.max_children = 100
pm.start_servers = 20
pm.min_spare_servers = 10
pm.max_spare_servers = 30
重启:
sudo systemctl restart php8.x-fpm
sudo apt install php-opcache
/etc/php/8.x/fpm/php.ini:
opcache.enable=1
opcache.memory_consumption=256
opcache.interned_strings_buffer=16
opcache.max_accelerated_files=10000
opcache.revalidate_freq=60
opcache.validate_timestamps=0 # 生产环境
APP_ENV=production
APP_DEBUG=false
php artisan config:cache
php artisan route:cache
php artisan view:cache
php artisan event:cache
注意:改了代码或配置后必须重新 cache
laravel-debugbartelescope(生产可关)User::with('posts')->get();
select() 减少字段Model::upsert(...)
SHOW VARIABLES LIKE 'slow_query%';
sudo apt install redis-server
.env:
CACHE_DRIVER=redis
SESSION_DRIVER=redis
QUEUE_CONNECTION=redis
Cache::remember('key', 600, function () {
return User::all();
});
php artisan queue:work --daemon
用 supervisor 守护:
sudo apt install supervisor
npm run build
gzip on;
gzip_types text/css application/javascript;
laravel-perfblackfiretop / htopnginx access log✅ APP_DEBUG=false
✅ OPcache 开启
✅ config/route/view cache
✅ Redis 缓存
✅ 队列异步
✅ Nginx + PHP-FPM
如果你愿意,可以告诉我:
我可以给你一套针对性配置示例。