Laravel 在 Debian 上运行缓慢可能是由于多种原因造成的,以下是一些常见的优化和加速方法:
1. 使用 Octane 加速 Laravel
Octane 是一个高性能的 Laravel 服务器,可以通过使用高能应用服务器(如 FrankenPHP、Open Swoole、Swoole 和 RoadRunner)来提高应用程序的性能。以下是启用 Octane 的步骤:
-
安装 Octane:
composer require laravel/octane
-
安装服务(以 FrankenPHP 为例):
php artisan octane:install --server=frankenphp
-
启用服务:
php artisan octane:start
-
配置 Nginx: 修改 Nginx 配置文件,将请求代理给 Octane 服务。例如:
location /index.php { try_files /not_exists @octane; } location / { try_files $uri $uri/ @octane; } location @octane { set $suffix ""; if ($uri = /index.php) { set $suffix?%query_string; } proxy_http_version 1.1; proxy_set_header Host $http_host; proxy_set_header Scheme $scheme; proxy_set_header SERVER_PORT $server_port; proxy_set_header REMOTE_ADDR $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; proxy_pass http://127.0.0.1:8000$suffix; }
2. 优化 PHP 配置
确保 PHP 配置文件(php.ini
)中的设置是优化的。例如:
-
内存限制:增加内存限制。
memory_limit = 256M
-
最大执行时间:增加最大执行时间。
max_execution_time = 300
-
OPcache:启用 OPcache 扩展。
zend_extension=opcache.so opcache.enable=1 opcache.validate_timestamps=1 opcache.fast_shutdown=1
3. 使用 Nginx + PHP-FPM
确保 Nginx 和 PHP-FPM 配置正确。以下是一个基本的配置示例:
Nginx 配置:
server { listen 80; server_name example.com; root /var/www/example/public; index index.php index.html index.htm; location / { try_files $uri $uri/ /index.php?$query_string; } location ~ \.php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; } location ~ /\.ht { deny all; } }
PHP-FPM 配置:
[www] listen = 127.0.0.1:9000 listen.owner = www-data listen.group = www-data user = www-data group = www-data pm = dynamic pm.max_children = 5 pm.start_servers = 2 pm.min_spare_servers = 1 pm.max_spare_servers = 3
4. 使用 Redis 加速缓存
安装并配置 Redis 作为 Laravel 的缓存驱动:
-
安装 Redis:
sudo apt install redis-server
-
配置 Laravel: 在
.env
文件中配置 Redis 缓存驱动:CACHE_DRIVER=redis SESSION_DRIVER=redis
5. 优化数据库查询
确保数据库查询是优化的。可以使用 Laravel 的 Eloquent ORM 的 Eager Loading 功能来减少 N+1 查询问题。
6. 使用 Supervisor 管理 PHP-FPM
使用 Supervisor 来管理 PHP-FPM 进程,确保服务在后台稳定运行:
-
安装 Supervisor:
sudo apt install supervisor
-
配置 Supervisor: 创建 Supervisor 配置文件
/etc/supervisor/conf.d/php7.4-fpm.conf
:[program:php7.4-fpm] process_name=%(program_name)s command=/usr/sbin/php7.4-fpm7.4 -F autostart=true autorestart=true user=www-data redirect_stderr=true stdout_logfile=/var/log/php7.4-fpm.log
-
重启 Supervisor:
sudo service supervisor restart
通过以上步骤,可以显著提高 Laravel 在 Debian 上的运行速度。根据具体情况,可能需要进一步调整和优化。