温馨提示×

怎么在centos优化laravel

小樊
40
2026-10-08 18:09:49
栏目: 智能运维

在 CentOS 上优化 Laravel,一般可以从系统层、PHP 层、Laravel 自身、缓存与队列、数据库、Web 服务器几个方面来做。下面给你一套比较实用、可落地的优化方案。


一、系统层面(CentOS)

1. 关闭不必要的服务

systemctl disable --now firewalld   # 如果用了云安全组
systemctl disable --now postfix

保留:nginx / php-fpm / redis / mysql

2. 调整文件描述符

ulimit -n 65535

永久生效:

/etc/security/limits.conf
* soft nofile 65535
* hard nofile 65535

3. 使用 SSD / 高 IO 磁盘

Laravel 大量读文件(config、routes、views),IO 很关键。


二、PHP 优化(PHP-FPM)

1. 使用 PHP 8.1+(推荐 8.2 / 8.3)

php -v

Laravel 10/11 在 PHP 8.2+ 性能提升明显。

2. 安装 OPcache

yum install php-opcache

/etc/php.d/opcache.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

3. PHP-FPM 配置

/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

三、Laravel 自身优化(非常重要)

1. 生产环境必须执行的命令

php artisan config:cache
php artisan route:cache
php artisan view:cache
php artisan event:cache

⚠️ 改代码后必须重新 cache

2. 关闭 debug

.env

APP_DEBUG=false
APP_ENV=production

3. 使用 Laravel Octane(高并发)

composer require laravel/octane
php artisan octane:install

使用 RoadRunner 或 Swoole


四、缓存与队列

1. 使用 Redis

.env

CACHE_DRIVER=redis
SESSION_DRIVER=redis
QUEUE_CONNECTION=redis

2. 启动队列

php artisan queue:work --daemon

用 systemd 或 supervisor 守护

3. 定时任务

crontab -e
* * * * * php /path/artisan schedule:run

五、数据库优化

1. 索引

$table->index('user_id');

2. 使用 Eager Loading

❌

User::all()->posts

✅

User::with('posts')->get();

3. 慢查询日志

SHOW VARIABLES LIKE 'slow_query_log';

六、Web 服务器(Nginx)

1. 开启 gzip

gzip on;
gzip_types text/css application/javascript;

2. 静态资源缓存

location ~* \.(js|css|png)$ {
    expires 30d;
}

七、监控与压测

  • htop
  • php artisan telescope(开发)
  • ab / wrk 压测
ab -n 1000 -c 100 http://site/

最简优化清单(直接照做)

✅ PHP 8.2 + OPcache
✅ config / route / view cache
✅ Redis 缓存 + 队列
✅ Nginx gzip
✅ supervisor 管理队列

如果你愿意,可以告诉我:

  • CentOS 版本
  • PHP 版本
  • Laravel 版本
  • 并发量 / 服务器配置

我可以给你一套精准配置。

0 踩