CI/CD Với GitHub Actions Cho Laravel

· 3 min read

Continuous Integration/Continuous Deployment (CI/CD) đảm bảo code của bạn được test và deploy tự động. GitHub Actions làm điều này dễ dàng và miễn phí cho các repository công khai.

File Workflow

Tạo file tại .github/workflows/laravel.yml.

1. Pipeline CI Tối Thiểu (Testing)

Workflow này chạy test của bạn mỗi khi push.

name: Laravel CI

on:
  push:
    branches: [ "main" ]
  pull_request:
    branches: [ "main" ]

jobs:
  laravel-tests:

    runs-on: ubuntu-latest

    services:
      mysql:
        image: mysql:8.0
        env:
          MYSQL_ROOT_PASSWORD: root
          MYSQL_DATABASE: laravel_test
        ports:
          - 3306:3306
        options: >-
          --health-cmd="mysqladmin ping"
          --health-interval=10s
          --health-timeout=5s
          --health-retries=3

    steps:
    - uses: actions/checkout@v4

    - name: Setup PHP
      uses: shivammathur/setup-php@v2
      with:
        php-version: '8.2'
        extensions: mbstring, xml, bcmath, mysql

    - name: Copy .env
      run: php -r "file_exists('.env') || copy('.env.example', '.env');"

    - name: Install Dependencies
      run: composer install -q --no-ansi --no-interaction --no-scripts --no-progress --prefer-dist

    - name: Generate Key
      run: php artisan key:generate

    - name: Directory Permissions
      run: chmod -R 777 storage bootstrap/cache

    - name: Execute tests (Unit and Feature tests) via PHPUnit
      env:
        DB_CONNECTION: mysql
        DB_DATABASE: laravel_test
        DB_PASSWORD: root
      run: vendor/bin/phpunit

2. Pipeline CD (Deploy Đơn Giản)

Để deploy, bạn thường SSH vào server và chạy script.

Thêm phần này như một job riêng (cần runs-on: ubuntu-latest):

  deploy:
    runs-on: ubuntu-latest
    needs: laravel-tests # Chỉ deploy nếu test pass
    if: github.ref == 'refs/heads/main' # Chỉ deploy nhánh main

    steps:
    - name: Deploy to Server
      uses: appleboy/ssh-action@master
      with:
        host: ${{ secrets.SSH_HOST }}
        username: ${{ secrets.SSH_USERNAME }}
        key: ${{ secrets.SSH_PRIVATE_KEY }}
        script: |
          cd /var/www/my-app
          git pull origin main
          composer install --no-dev --optimize-autoloader
          php artisan migrate --force
          php artisan config:cache
          php artisan event:cache
          php artisan route:cache
          php artisan view:cache
          # Restart queue worker được quản lý bởi Supervisor
          sudo supervisorctl restart all

Secrets: Bạn phải cấu hình SSH_HOST, SSH_USERNAME, và SSH_PRIVATE_KEY trong GitHub Repository Settings > Secrets and variables > Actions.

Lợi Ích

  1. Tự Tin: Bạn không bao giờ làm hỏng production vì test chạy trước khi deploy.
  2. Tốc Độ: Không còn phải FTP file thủ công hoặc SSH để pull code.
  3. Nhất Quán: Quy trình giống nhau mỗi lần.

Bình luận