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

Bài 22: Production Deployment & Monitoring

Zero-downtime deployment (Envoyer, Deployer). Laravel Telescope, Pulse monitoring. Sentry error tracking, structured logging. Prometheus metrics, health checks. Scaling strategies (Octane, load balancer, queue workers).

💻 Lập trình — Bài 22 Bài 22: Production Deployment & Monitoring

Laravel: Từ Cơ bản đến Nâng cao

Phần 6: Testing, Docker & Production

xdev.asia

1. Zero-Downtime Deployment

# 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 Pulse Monitoring

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. Sentry Error Tracking

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

4. Structured Logging

// 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. Health Checks

// 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. Scaling Strategies

Chiến lượcMô tả
OctaneSwoole/FrankenPHP — giữ app trong memory
Queue WorkersScale horizontal với nhiều workers
Read ReplicasTách read/write database
CDNStatic assets, media files
Load BalancerNginx/HAProxy phân tải
Redis ClusterCache & session scaling

Chúc mừng bạn đã hoàn thành series Laravel: Từ Cơ bản đến Nâng cao! 🎉