在 Linux 环境下优化 Laravel 性能,通常可以从 PHP、Laravel 自身、数据库、缓存、Web 服务器、系统层面 多个角度入手。下面是一套比较系统、可落地的优化方案。
php artisan config:cache
php artisan route:cache
php artisan view:cache
php artisan event:cache
部署后务必执行,避免运行时解析。
.env
APP_DEBUG=false
APP_ENV=production
composer require laravel/octane
php artisan octane:install
使用 Swoole / RoadRunner:
php artisan octane:start --server=swoole
Laravel 10/11 对 PHP 8+ 有显著性能提升。
sudo apt install php-opcache
php.ini 示例:
opcache.enable=1
opcache.memory_consumption=256
opcache.max_accelerated_files=20000
opcache.revalidate_freq=60
opcache.validate_timestamps=0
生产环境
validate_timestamps=0
www.conf:
pm = dynamic
pm.max_children = 100
pm.start_servers = 20
pm.min_spare_servers = 10
pm.max_spare_servers = 30
.env
CACHE_DRIVER=redis
SESSION_DRIVER=redis
QUEUE_CONNECTION=redis
Cache::remember('users', 600, fn () => User::all());
User::with('posts')->get();
ALTER TABLE users ADD INDEX (email);
slow_query_log = 1
long_query_time = 1
避免每次请求新建连接。
gzip on;
gzip_types text/css application/javascript;
location ~* \.(js|css|png)$ {
expires 30d;
}
php artisan queue:work redis
[program:laravel-worker]
command=php /var/www/artisan queue:work redis
autostart=true
ulimit -n 65535
free -h
确保不频繁 OOM。
数据库 IO 提升明显。
php artisan route:list 检查路由复杂度✅ PHP 8.3 + OPcache
✅ Laravel Octane (Swoole)
✅ Redis
✅ Nginx
✅ MySQL 索引 + 慢查询
✅ 队列异步
如果你愿意,可以告诉我:
我可以给你一份 针对性的优化方案。