在 Debian 上优化 Laravel,一般从 系统层、PHP 层、Laravel 本身、数据库、缓存与部署 几个方面入手。下面给你一套实战向的优化清单,适合生产环境。
sudo apt update && sudo apt upgrade -y
建议使用:
sudo apt install -y \
nginx \
php8.2-fpm \
php8.2-mysql \
php8.2-redis \
php8.2-curl \
php8.2-mbstring \
php8.2-xml \
php8.2-zip \
php8.2-bcmath \
php8.2-gd \
unzip \
git \
curl
php-fpm 配置编辑:
/etc/php/8.2/fpm/pool.d/www.conf
推荐调整:
pm = dynamic
pm.max_children = 50
pm.start_servers = 10
pm.min_spare_servers = 5
pm.max_spare_servers = 20
根据服务器内存调整:
pm.max_children = 30pm.max_children = 60php.ini/etc/php/8.2/fpm/php.ini
memory_limit = 256M
upload_max_filesize = 20M
post_max_size = 20M
max_execution_time = 120
opcache.enable=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=16
opcache.max_accelerated_files=10000
重启:
sudo systemctl restart php8.2-fpm
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 $realpath_root$fastcgi_script_name;
include fastcgi_params;
}
location ~ /\.ht {
deny all;
}
}
开启 gzip:
gzip on;
gzip_types text/css application/javascript application/json;
APP_ENV=production
APP_DEBUG=false
php artisan config:cache
php artisan route:cache
php artisan view:cache
php artisan event:cache
⚠️ 注意:
route:cache 不支持闭包路由composer install --optimize-autoloader --no-dev
CACHE_DRIVER=redis
SESSION_DRIVER=redis
QUEUE_CONNECTION=redis
安装 Redis:
sudo apt install redis-server
sudo systemctl enable redis
php artisan queue:work --daemon
使用 Supervisor(强烈推荐):
sudo apt install supervisor
示例:
[program:laravel-worker]
command=php /var/www/laravel/artisan queue:work --sleep=3 --tries=3
autostart=true
autorestart=true
user=www-data
innodb_buffer_pool_size = 512M
innodb_log_file_size = 128M
max_connections = 150
select() 控制字段with() 解决 N+1sudo phpdismod xdebug
避免直接用 git pull:
php artisan storage:linkphp artisan migrate --forcehtopjournalctl -u php8.2-fpmcomposer install --optimize-autoloader --no-dev
php artisan config:cache
php artisan route:cache
php artisan view:cache
php artisan event:cache
你可以告诉我:
我可以给你 针对你服务器的定制优化方案。