在 CentOS 上优化 Laravel,通常可以从 系统层面、PHP 层面、Laravel 自身、数据库、缓存、Web 服务器 几个方向来做。下面是一套比较实用、可落地的优化方案。
systemctl disable --now firewalld # 如有外部防火墙可关
systemctl disable --now postfix
(仅示例,按需关闭)
ulimit -n 65535
永久生效:
/etc/security/limits.conf
* soft nofile 65535
* hard nofile 65535
Laravel 对磁盘 IO 较敏感(日志、缓存、session)。
php -v
如果还是 7.2/7.4,建议升级。
yum install php-opcache
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 # 生产环境
vim /etc/php-fpm.d/www.conf
关键参数:
pm = dynamic
pm.max_children = 100
pm.start_servers = 20
pm.min_spare_servers = 10
pm.max_spare_servers = 30
worker_processes auto;
worker_connections 10240;
gzip on;
gzip_min_length 1k;
gzip_comp_level 5;
gzip_types text/css application/javascript application/json;
location ~* \.(js|css|png|jpg|svg|woff2)$ {
expires 30d;
access_log off;
}
进入项目目录:
php artisan config:cache
php artisan route:cache
php artisan view:cache
php artisan optimize
生产环境建议:
APP_ENV=production
APP_DEBUG=false
CACHE_DRIVER=redis
SESSION_DRIVER=redis
QUEUE_CONNECTION=redis
安装 Redis:
yum install redis
systemctl enable --now redis
如不需要:
VerifyCsrfToken(API) sessions(API)innodb_buffer_pool_size = 1G
query_cache_type = 0
max_connections = 500
php artisan migrate --force
确保常用查询字段有索引。
select *with() 解决 N+1chunk() / lazy()php artisan queue:work --daemon
用 supervisor 保活:
yum install supervisor
crontab -e
* * * * * php /path/artisan schedule:run
logrotate| 优化项 | 提升效果 |
|---|---|
| OPcache | 2–5x |
| config/route cache | 30–50% |
| Redis | 明显 |
| PHP 8 | 20–40% |
如果你愿意,我可以:
你可以直接说:
“我是 CentOS 7 / PHP 8.1 / Laravel 10,给我一套配置”