在 Linux 上优化 Laravel 性能,通常从 PHP 层面、Laravel 层面、服务器/系统层面、数据库层面 入手。下面是一套比较实用、生产环境常见的优化方案。
# 缓存配置
php artisan config:cache
# 路由缓存
php artisan route:cache
# 视图缓存
php artisan view:cache
# 事件缓存(Laravel 8+)
php artisan event:cache
⚠️ 注意:
.env、config、routes 后必须重新 cache.env
APP_DEBUG=false
APP_ENV=production
Laravel 是 PHP 框架,OPcache 能显著提升性能。
sudo apt install php-opcache
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
生产环境
validate_timestamps=0,改代码后重启 PHP
推荐组合:
pm = dynamic
pm.max_children = 100
pm.start_servers = 20
pm.min_spare_servers = 10
pm.max_spare_servers = 30
根据内存调整:
gzip on;
gzip_types text/css application/javascript application/json;
静态资源走 Nginx,不走 PHP。
Schema::table('users', function (Blueprint $table) {
$table->index('email');
});
❌ 错误
$users = User::all();
foreach ($users as $user) {
$user->posts;
}
✅ 正确
$users = User::with('posts')->get();
可以用:
php artisan Telescope # 或 debugbar 观察 SQL
.env
CACHE_DRIVER=redis
QUEUE_CONNECTION=redis
SESSION_DRIVER=redis
安装 Redis:
sudo apt install redis-server
php artisan queue:work --daemon
建议用:
supervisor 守护进程基于 Swoole / RoadRunner
composer require laravel/octane
php artisan octane:install
php artisan octane:start
⚠️ 需要代码无全局状态问题
Cache::remember('users', 60, function () {
return User::all();
});
ulimit -n 65535
Nginx / PHP-FPM Worker 数合理配置
✅ 最佳实践:
如果你愿意,可以告诉我:
我可以给你一套 针对性的优化方案。