在 Debian 上优化 Laravel,通常从 系统层、PHP 层、Laravel 层、数据库与缓存、Web 服务器 这几个维度来做。下面给你一套比较完整、可落地的优化方案(适用于生产环境)。
systemctl list-units --type=service --state=running
systemctl disable 不需要的服务
ulimit -n
编辑:
sudo vim /etc/security/limits.conf
添加:
* soft nofile 65535
* hard nofile 65535
sudo apt update
sudo apt install php8.2 php8.2-fpm php8.2-cli \
php8.2-mysql php8.2-curl php8.2-mbstring \
php8.2-xml php8.2-zip php8.2-redis php8.2-opcache
编辑:
sudo vim /etc/php/8.2/fpm/pool.d/www.conf
推荐配置(4 核 8G 服务器示例):
pm = dynamic
pm.max_children = 50
pm.start_servers = 10
pm.min_spare_servers = 5
pm.max_spare_servers = 20
重载:
sudo systemctl restart php8.2-fpm
编辑:
sudo vim /etc/php/8.2/fpm/conf.d/10-opcache.ini
推荐配置:
opcache.enable=1
opcache.memory_consumption=256
opcache.interned_strings_buffer=32
opcache.max_accelerated_files=20000
opcache.validate_timestamps=0
opcache.revalidate_freq=0
validate_timestamps=0适合生产环境,代码更新后需重启 PHP-FPM
php artisan config:cache
php artisan route:cache
php artisan view:cache
php artisan event:cache
⚠️ 注意:
route:cache 不支持闭包路由.env
APP_ENV=production
APP_DEBUG=false
composer install --optimize-autoloader --no-dev
或者:
composer dump-autoload -o
php artisan queue:work --daemon
建议用 supervisor 管理队列。
安装 Redis:
sudo apt install redis-server
.env
CACHE_DRIVER=redis
SESSION_DRIVER=redis
QUEUE_CONNECTION=redis
sudo vim /etc/redis/redis.conf
maxmemory 256mb
maxmemory-policy allkeys-lru
server {
listen 80;
server_name example.com;
root /var/www/laravel/public;
index index.php;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php8.2-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
location ~ /\.ht {
deny all;
}
}
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
innodb_buffer_pool_size = 1G
innodb_log_file_size = 256M
max_connections = 200
select *with() 解决 N+1 问题sudo apt install supervisor
示例:
[program:laravel-worker]
command=php /var/www/laravel/artisan queue:work --tries=3
autostart=true
autorestart=true
php artisan cache:clear
php artisan config:clear
php artisan route:clear
| 项目 | 优化前 | 优化后 |
|---|---|---|
| 请求响应 | 300ms | 50–80ms |
| 并发能力 | 低 | 提升 3–5 倍 |
| CPU 占用 | 高 | 明显下降 |
✅ PHP 8.x + Opcache
✅ Laravel config / route / view cache
✅ Redis 缓存 & 队列
✅ Nginx + Gzip
✅ Composer 优化自动加载
✅ supervisor 管理队列
如果你愿意,可以告诉我:
我可以帮你 定制一套最优配置方案。