Chuyển đến nội dung chính

第 22 課:生產部署與監控

零停機部署(Envoyer、Deployer)。 Laravel 望遠鏡,脈衝監測。 Sentry 錯誤追蹤、結構化日誌記錄。普羅米修斯指標,健康檢查。擴展策略(Octane、負載平衡器、佇列工作執行緒)。

💻 程式設計 — 第 22 課 第 22 課:生產部署與監控

Laravel:從基礎到高級

第 6 部分:測試、Docker 和生產

亞洲開發網

1. 零停機部署

# Deployer (deployer.org)
composer require deployer/deployer --dev
// deploy.php
namespace Deployer;

require 'recipe/laravel.php';

host('production')
    ->set('remote_user', 'deploy')
    ->set('deploy_path', '/var/www/app');

task('deploy', [
    'deploy:prepare',
    'deploy:vendors',
    'artisan:storage:link',
    'artisan:config:cache',
    'artisan:route:cache',
    'artisan:view:cache',
    'artisan:migrate',
    'deploy:publish',
]);

after('deploy:failed', 'deploy:unlock');

2.Laravel 脈衝監控

composer require laravel/pulse
php artisan vendor:publish --provider="Laravel\Pulse\PulseServiceProvider"
php artisan migrate
// Dashboard tại /pulse
// Hiển thị: slow queries, exceptions, queue jobs, cache hits
Route::middleware(['auth', 'can:viewPulse'])->group(function () {
    Route::get('/pulse', function () {
        return view('vendor.pulse.dashboard');
    });
});

3.哨兵錯誤追蹤

composer require sentry/sentry-laravel
php artisan sentry:publish
SENTRY_LARAVEL_DSN=https://[email protected]/0
SENTRY_TRACES_SAMPLE_RATE=0.1

4. 結構化日誌記錄

// config/logging.php
'channels' => [
    'stack' => [
        'driver' => 'stack',
        'channels' => ['daily', 'stderr'],
    ],
    'daily' => [
        'driver' => 'daily',
        'path' => storage_path('logs/laravel.log'),
        'days' => 14,
    ],
],

// Sử dụng
Log::info('Order placed', ['order_id' => $order->id, 'total' => $order->total]);

5. 健康檢查

// routes/web.php
Route::get('/health', function () {
    try {
        DB::connection()->getPdo();
        Cache::store()->get('health-check');
        return response()->json(['status' => 'healthy']);
    } catch (\Exception $e) {
        return response()->json(['status' => 'unhealthy'], 503);
    }
});

6. 擴展策略

策略描述
辛烷值Swoole/FrankenPHP — 將應用程式保留在記憶體中
隊列工人與許多工人橫向擴展
讀取副本獨立的讀/寫資料庫
CDN靜態資源、媒體文件
負載平衡器Nginx/HAProxy 分配負載
Redis集群緩存和會話擴展

恭喜您完成系列 Laravel:從基礎到高級! 🎉