Simplified Guide: Deploying Laravel to AWS Serverless with Optimizations

Overview

This guide walks you through deploying your Laravel application to AWS using serverless architecture. It simplifies the core concepts and gives step-by-step instructions with real-world Laravel examples.

Prerequisites

  • PHP (v8.2 recommended)
  • Composer
  • Node.js
  • Serverless CLI
  • AWS CLI with credentials configured

Step 1: Set Up AWS Lambda

  1. Go to AWS Console > Services > Lambda.
  2. Create a new Lambda function.
  3. Configure AWS CLI locally with aws configure.

Step 2: Create Laravel Project

laravel new laravel-serverless
cd laravel-serverless
php artisan migrate
npm install && npm run build

Step 3: Install Bref

composer require bref/bref bref/laravel-bridge --update-with-dependencies
php artisan vendor:publish --tag=serverless-config

This creates a serverless.yml file.

Step 4: Configure serverless.yml

service: laravel

provider:
  name: aws
  region: us-east-1
  runtime: php-82-fpm

functions:
  web:
    handler: public/index.php
    timeout: 28
    events:
      - httpApi: '*'

plugins:
  - ./vendor/bref/bref

Step 5: Deploy Your App

serverless deploy

Console output will give you a URL (API Gateway).

Step 6: Serve Static Assets (CSS/JS)

Install serverless-lift:

serverless plugin install -n serverless-lift

Update serverless.yml:

constructs:
  website:
    type: server-side-website
    assets:
      '/build/*': public/build

Deploy again:

serverless deploy

Step 7: Handle Sessions, Logs, Cache

  • Logs: CloudWatch
  • Sessions: Cookies or DynamoDB
  • Cache: DynamoDB or SQS

Step 8: Reduce Cold-Start Delays

Keep Lambda warm:

functions:
  web:
    events:
      - schedule:
          rate: rate(5 minutes)
          input:
            warmer: true

Remove dev packages:

composer install --no-dev

Optimize AWS SDK size:

"scripts": {
  "pre-autoload-dump": "Aws\\Script\\Composer\\Composer::removeUnusedServices"
},
"extra": {
  "aws/aws-sdk-php": ["DynamoDb", "S3", "Sqs"]
}

Step 9: Use Laravel Octane

composer require laravel/octane
php artisan octane:install

Update serverless.yml handler:

functions:
  web:
    handler: Bref\LaravelBridge\Http\OctaneHandler
    runtime: php-82
serverless deploy

Step 10: Run Artisan in Lambda

serverless bref:cli --args="route:list"

Bonus: Analyze Laravel Code

Install Laravel query analyzer:

composer require beyondcode/laravel-query-detector --dev

Or use PHP Insights:

composer require nunomaduro/phpinsights --dev
php artisan insights

Wrap Up

You’ve deployed Laravel to a serverless architecture on AWS! Use Bref, S3, CloudFront, and Laravel Octane to get max performance while keeping costs in control.

Originally Learned from this article

No comments:

Post a Comment