Deploying a Laravel application to a Digital Ocean droplet can be streamlined using GitHub Actions. This process automates your deployment, ensuring a consistent and error-free deployment each time you push new changes to your repository. Here's a step-by-step guide on how to achieve this.
Step 1: Setting Up Your Digital Ocean Droplet
Ensure your Digital Ocean droplet is configured with a LAMP or LEMP stack. You can use Digital Ocean's marketplace for a quick setup.
Step 2: SSH Key Setup
Generate an SSH key on your local machine (if you haven't already):
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
Add the public key (id_rsa.pub) to the ~/.ssh/authorized_keys file on your Digital Ocean droplet.
Step 3: GitHub Secrets Configuration
In your GitHub repository: Go to Settings > Secrets. Add the following secrets:
- DO_SSH_KEY: Your private SSH key (id_rsa).
- DO_HOST: Your Digital Ocean droplet IP address.
- DO_USERNAME: The username on your droplet (typically root).
Step 4: Creating the GitHub Action Workflow
In your GitHub repository, create a directory named .github/workflows. Create a new file named laravel_deploy.yml. Add the following content to laravel_deploy.yml:
name: Deploy Laravel to Digital Ocean
on:
push:
branches:
- main
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Setup SSH
run: |
mkdir -p ~/.ssh/
echo "${{ secrets.DO_SSH_KEY }}" > ~/.ssh/id_rsa
chmod 600 ~/.ssh/id_rsa
ssh-keyscan -H ${{ secrets.DO_HOST }} >> ~/.ssh/known_hosts
- name: Deploy to Digital Ocean
run: |
scp -r ./* ${{ secrets.DO_USERNAME }}@${{ secrets.DO_HOST }}:/var/www/html
ssh ${{ secrets.DO_USERNAME }}@${{ secrets.DO_HOST }} "cd /var/www/html && composer install && php artisan migrate"
Step 5: Pushing Changes
This workflow does the following on every push to the main branch:
- Checks out the code.
- Sets up SSH access.
- Copies the project files to the Digital Ocean droplet.
- Runs composer install and php artisan migrate on the droplet.
Now, every time you push changes to the main branch of your GitHub repository, the GitHub Action will automatically deploy your Laravel application to your Digital Ocean droplet.
Automating your Laravel deployment using GitHub Actions and Digital Ocean simplifies the process and reduces the potential for human error. It ensures that your application is always up-to-date with the latest changes in your repository. For more advanced workflows, consider adding steps for running tests, caching dependencies, or setting up zero-downtime deployment. The flexibility of GitHub Actions allows for a highly customized deployment process tailored to your project's needs.
Happy coding!