在 CentOS 上优化 Laravel,通常可以从系统层、PHP 层、Laravel 自身、Web 服务器、数据库、缓存几个方面入手。下面按实战角度给你一套比较完整的优化方案。
systemctl disable firewalld --now # 如果用了云安全组可关
systemctl disable postfix
只保留:nginx / php-fpm / mysql / redis
ulimit -n 65535
永久:
vim /etc/security/limits.conf
* soft nofile 65535
* hard nofile 65535
fallocate -l 2G /swapfile
chmod 600 /swapfile
mkswap /swapfile
swapon /swapfile
yum install epel-release -y
yum install https://rpms.remirepo.net/enterprise/remi-release-7.rpm
yum-config-manager --enable remi-php82
yum install php php-fpm php-mysqlnd php-redis php-opcache
memory_limit = 256M
upload_max_filesize = 20M
post_max_size = 20M
max_execution_time = 60
cgi.fix_pathinfo=0
[opcache]
opcache.enable=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=10000
opcache.revalidate_freq=60
opcache.validate_timestamps=0 # 生产环境
www.conf
pm = dynamic
pm.max_children = 50
pm.start_servers = 10
pm.min_spare_servers = 5
pm.max_spare_servers = 20
worker_processes auto;
worker_connections 10240;
keepalive_timeout 30;
gzip on;
gzip_min_length 1k;
gzip_comp_level 5;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
fastcgi_pass unix:/run/php-fpm/www.sock;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
php artisan config:cache
php artisan route:cache
php artisan view:cache
php artisan optimize (Laravel 8+ 已合并)
.env
APP_DEBUG=false
APP_ENV=production
LOG_CHANNEL=daily
LOG_LEVEL=error
CACHE_DRIVER=redis
SESSION_DRIVER=redis
QUEUE_CONNECTION=redis
php artisan queue:work --daemon
建议用 supervisor:
[program:laravel-worker]
command=php /var/www/artisan queue:work --tries=3
autostart=true
autorestart=true
innodb_buffer_pool_size = 1G
max_connections = 200
query_cache_type = 0
select() 避免 select *with() 解决 N+1composer install --optimize-autoloader --no-dev
top
htop
php-fpm status
redis-cli monitor
✅ PHP 8 + OPCache
✅ Laravel config/route/view cache
✅ Redis 缓存 & 队列
✅ Nginx + php-fpm 调优
✅ 关闭 debug
如果你愿意,可以告诉我:
我可以给你一套针对性配置模板。