How to Deploy a Laravel Application to AWS

Laravel is a popular PHP framework for building web applications. In this tutorial, we will guide you through the process of deploying a Laravel application to AWS (Amazon Web Services). Deploying your application to AWS offers scalability, reliability, and security benefits.

Before diving into the deployment process, make sure you have the following prerequisites:

  • A Laravel application with completed development and testing.
  • An AWS account with the necessary permissions to create and manage AWS resources.
  • Basic familiarity with AWS services like EC2, RDS, S3, and IAM.

Let’s get started!

Step 1: Set up the AWS Infrastructure

First, we need to set up the necessary AWS resources for our Laravel application.

1.1 Create an EC2 Instance

An EC2 instance will host our Laravel application. Follow these steps to create an EC2 instance:

  1. Go to the AWS Management Console and navigate to the EC2 service.
  2. Click on the “Launch Instance” button and choose an Amazon Machine Image (AMI). We recommend using the latest version of Amazon Linux or Ubuntu.

  3. Select an instance type based on your application’s requirements. A t2.micro instance is a good starting point for small applications.

  4. Configure instance details. Ensure that the instance is launched within a public subnet and has a public IP assigned.

  5. Add storage as required. The default settings should be sufficient for most applications.

  6. Configure security groups. Open port 22 (SSH) and any other ports your Laravel application requires (e.g., port 80 for HTTP or port 443 for HTTPS).

  7. Review the instance details and launch the instance. Choose an existing key pair or create a new one to securely connect to the instance.

  8. Once the instance is launched, note down the public IP or DNS name. You will need this to access your Laravel application.

1.2 Create an RDS Database

A database is essential for storing your Laravel application’s data. We will use Amazon RDS to create a managed database instance.

  1. Navigate to the RDS service in the AWS Management Console.
  2. Click on “Create database” and choose the database engine that matches your Laravel application’s requirements (MySQL, PostgreSQL, etc.).

  3. Select the appropriate instance type based on your application’s needs. Consider the expected number of concurrent connections and size of your dataset.

  4. Configure the database instance details. Provide a database name, master username, and password.

  5. Set up the networking and security settings. Create a new VPC security group and allow inbound access on the database port (e.g., port 3306 for MySQL).

  6. Review the configuration and create the database instance.

  7. Once the database instance is created, note down the hostname, port, database name, username, and password. We will need these details to configure our Laravel application later.

1.3 Create an S3 Bucket

If your Laravel application requires storage for file uploads, images, or other assets, we can use Amazon S3 for object storage.

  1. Go to the S3 service in the AWS Management Console.
  2. Click on “Create bucket” and provide a unique name for your bucket.

  3. Choose the AWS region where you want your S3 bucket to be located.

  4. Configure the bucket options and permissions as required.

  5. Review and create the bucket.

  6. Make sure to note down your S3 bucket name. We will need this information when configuring the Laravel application.

Now that we have set up the necessary AWS resources, let’s move on to configuring our Laravel application.

Step 2: Configure the Laravel Application

In this step, we will update the Laravel application’s configuration to work with the AWS resources we created in the previous step.

2.1 Update .env File

The .env file in your Laravel application contains environment-specific configuration settings. Update the file with the following AWS-related settings:

DB_CONNECTION=mysql
DB_HOST=<RDS_HOSTNAME>
DB_PORT=<RDS_PORT>
DB_DATABASE=<RDS_DATABASE>
DB_USERNAME=<RDS_USERNAME>
DB_PASSWORD=<RDS_PASSWORD>

AWS_ACCESS_KEY_ID=<YOUR_AWS_ACCESS_KEY>
AWS_SECRET_ACCESS_KEY=<YOUR_AWS_SECRET_ACCESS_KEY>
AWS_DEFAULT_REGION=<YOUR_AWS_REGION>
AWS_BUCKET=<YOUR_S3_BUCKET>

Replace the placeholders (<RDS_HOSTNAME>, <RDS_PORT>, <RDS_DATABASE>, <RDS_USERNAME>, <RDS_PASSWORD>, <YOUR_AWS_REGION>, <YOUR_S3_BUCKET>) with the respective values from your AWS resources.

2.2 Install AWS SDK

To work with AWS services from your Laravel application, we need to install the AWS SDK using Composer. Open a terminal at the root of your Laravel application and run the following command:

composer require aws/aws-sdk-php

This will download and install the AWS SDK in your vendor directory.

2.3 Update S3 Configuration

Open the config/filesystems.php file in your Laravel application and update the disks array with the following AWS S3 configuration:

's3' => [
    'driver' => 's3',
    'key' => env('AWS_ACCESS_KEY_ID'),
    'secret' => env('AWS_SECRET_ACCESS_KEY'),
    'region' => env('AWS_DEFAULT_REGION'),
    'bucket' => env('AWS_BUCKET'),
],

2.4 Update Queue Configuration

If your Laravel application uses a queue system (e.g., Laravel Horizon or AWS SQS), update the config/queue.php file with the appropriate configuration settings for your queue driver.

Step 3: Deploy the Laravel Application to EC2

We are now ready to deploy the Laravel application to the EC2 instance we created earlier.

3.1 Install the Application Dependencies

Connect to your EC2 instance using SSH. If you are on macOS or Linux, open a terminal and run the following command:

ssh -i /path/to/your/key.pem ec2-user@<PUBLIC_IP_OR_DNS>

If you are on Windows, you can use a tool like PuTTY to connect to the instance.

Once connected, navigate to the /var/www/html directory (or the directory where you want to deploy your Laravel application) and clone your application’s repository:

cd /var/www/html
git clone <REPOSITORY_URL> .

Replace <REPOSITORY_URL> with the URL of your application’s repository.

Install the application dependencies using Composer:

composer install --no-dev

This will install the necessary packages defined in your composer.json file.

3.2 Set File Permissions

Set the appropriate file permissions for your Laravel application:

sudo chown -R apache:apache /var/www/html
sudo chmod -R 755 /var/www/html/storage

3.3 Generate Application Key

Generate a new application key using the artisan command:

php artisan key:generate --show

Copy the generated key as we will use it in the next step.

3.4 Configure the Web Server

We need to configure the web server (Apache or Nginx) to serve our Laravel application.

3.4.1 Apache Configuration

Create a new virtual host by creating a file in /etc/httpd/conf.d/ with the .conf extension (e.g., /etc/httpd/conf.d/mylaravelapp.conf) and add the following configuration:

<VirtualHost *:80>
    ServerName yourdomain.com
    DocumentRoot /var/www/html/public

    <Directory /var/www/html/public>
       AllowOverride All
    </Directory>

    ErrorLog /var/log/httpd/mylaravelapp-error.log
    CustomLog /var/log/httpd/mylaravelapp-access.log combined
</VirtualHost>

Replace yourdomain.com with your domain name or the public IP of your EC2 instance.

3.4.2 Nginx Configuration

Create a new server block in the Nginx configuration file (/etc/nginx/sites-available/default or /etc/nginx/conf.d/default.conf) with the following configuration:

server {
    listen 80;
    server_name yourdomain.com;
    root /var/www/html/public;

    index index.php index.html index.htm;

    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    location ~ .php$ {
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

    access_log /var/log/nginx/mylaravelapp-access.log;
    error_log /var/log/nginx/mylaravelapp-error.log;
}

Replace yourdomain.com with your domain name or the public IP of your EC2 instance.

Restart the web server to apply the changes:

sudo service httpd restart   # For Apache
sudo service nginx restart   # For Nginx

3.5 Test the Application

Access your Laravel application in a web browser using the public IP or DNS name of your EC2 instance. You should see your Laravel application up and running.

Step 4: Configure Automatic Deployment

To streamline your application deployment process, you can set up automatic deployments using AWS services like AWS CodeCommit and AWS CodePipeline.

4.1 Create a CodeCommit Repository

Create a new CodeCommit repository in the AWS Management Console. Follow the instructions to create an empty repository.

4.2 Push Your Laravel Application to CodeCommit

Push your Laravel application to the CodeCommit repository using the following commands:

aws configure   # Configure AWS credentials if not already done

cd /path/to/your/laravel/app
git init
git add .
git commit -m "Initial commit"
git remote add origin <YOUR_CODECOMMIT_REPO_URL>
git push -u origin master

Replace <YOUR_CODECOMMIT_REPO_URL> with the URL of your CodeCommit repository.

4.3 Create a CodePipeline

Create a new CodePipeline in the AWS Management Console using the following steps:

  1. Select the CodeCommit repository you created earlier as the source provider.
  2. Configure a build stage to build and test your Laravel application. You can use tools like AWS CodeBuild or a custom build script.

  3. Add a deploy stage to deploy your Laravel application to the EC2 instance. You can use AWS CodeDeploy or a custom deployment script.

  4. Review and create the CodePipeline.

Now whenever you push changes to your CodeCommit repository, AWS CodePipeline will automatically trigger the build and deployment process.

Conclusion

Congratulations! You have successfully deployed your Laravel application to AWS. By utilizing AWS services like EC2, RDS, S3, and CodePipeline, you can ensure scalability, reliability, and security for your Laravel application. Experiment with additional AWS services like caching (ElastiCache), CDN (CloudFront), and monitoring (CloudWatch) to further optimize your application’s performance. Happy coding!

Related Post