温馨提示×

centos怎么优化laravel

小樊
43
2026-09-17 23:58:19
栏目: 智能运维

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


一、系统层面优化(CentOS)

1. 关闭不必要的服务

systemctl disable --now firewalld   # 如有外部防火墙可关
systemctl disable --now postfix

(仅示例,按需关闭)

2. 调整文件描述符

ulimit -n 65535

永久生效:

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

3. 使用 SSD / 高 IO 磁盘

Laravel 对磁盘 IO 较敏感(日志、缓存、session)。


二、PHP 优化(非常关键)

1. 使用 PHP 8.x(推荐 8.1+)

php -v

如果还是 7.2/7.4,建议升级。

2. 安装 OPcache

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  # 生产环境

3. PHP-FPM 优化

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

三、Web 服务器优化(Nginx 推荐)

1. Nginx 基本优化

worker_processes auto;
worker_connections 10240;

gzip on;
gzip_min_length 1k;
gzip_comp_level 5;
gzip_types text/css application/javascript application/json;

2. 静态资源走 Nginx

location ~* \.(js|css|png|jpg|svg|woff2)$ {
    expires 30d;
    access_log off;
}

四、Laravel 自身优化(必做)

进入项目目录:

php artisan config:cache
php artisan route:cache
php artisan view:cache
php artisan optimize

生产环境建议:

APP_ENV=production
APP_DEBUG=false

五、缓存 & Session 优化(非常重要)

1. 使用 Redis

CACHE_DRIVER=redis
SESSION_DRIVER=redis
QUEUE_CONNECTION=redis

安装 Redis:

yum install redis
systemctl enable --now redis

2. 关闭无用中间件

如不需要:

  • VerifyCsrfToken(API)
  • sessions(API)

六、数据库优化(MySQL / MariaDB)

1. 基础参数

innodb_buffer_pool_size = 1G
query_cache_type = 0
max_connections = 500

2. 加索引

php artisan migrate --force

确保常用查询字段有索引。

3. 使用 Laravel 查询优化

  • 避免 select *
  • 使用 with() 解决 N+1
  • 使用 chunk() / lazy()

七、队列 & 定时任务

1. 队列

php artisan queue:work --daemon

用 supervisor 保活:

yum install supervisor

2. 定时任务

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

八、日志 & 监控

  • 关闭 debug 日志
  • 使用 logrotate
  • 可选:
    • Laravel Telescope(开发)
    • Sentry / Prometheus(生产)

九、简单性能对比(典型效果)

优化项 提升效果
OPcache 2–5x
config/route cache 30–50%
Redis 明显
PHP 8 20–40%

如果你愿意,我可以:

  • ✅ 按你的 CentOS 版本 + PHP 版本 给具体命令
  • ✅ 给你一套 生产环境 nginx + php-fpm 完整配置
  • ✅ 帮你排查 当前 Laravel 慢的原因

你可以直接说:

“我是 CentOS 7 / PHP 8.1 / Laravel 10,给我一套配置”

0 踩