GitHub Actions miễn phí cho public repo và có 2000 phút/tháng cho private repo. Đây là setup mình dùng cho hầu hết dự án.
Workflow cơ bản: Test + Deploy
# .github/workflows/deploy.yml
name: CI/CD
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: 20
cache: 'npm'
- run: npm ci
- run: npm test
- run: npm run lint
deploy:
needs: test
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Deploy to server
uses: appleboy/ssh-action@v1
with:
host: ${{ secrets.SERVER_HOST }}
username: ${{ secrets.SERVER_USER }}
key: ${{ secrets.SSH_KEY }}
script: |
cd /app
git pull
npm ci --production
pm2 restart app
Chạy test với nhiều phiên bản
jobs:
test:
strategy:
matrix:
node-version: [18, 20, 22]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
- run: npm ci && npm test
Cache để build nhanh hơn
- name: Cache node_modules
uses: actions/cache@v4
with:
path: ~/.npm
key: ${{ runner.os }}-npm-${{ hashFiles('**/package-lock.json') }}
restore-keys: ${{ runner.os }}-npm-
Chạy khi có tag (release)
on:
push:
tags:
- 'v*'
jobs:
release:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: npm ci && npm run build
- name: Create Release
uses: softprops/action-gh-release@v2
with:
files: dist/*
Tips
- Secrets: Đặt ở repo Settings → Secrets, KHÔNG hardcode trong workflow
-
npm cithaynpm install: nhanh hơn, deterministic -
needs: test: Deploy chỉ chạy khi test pass - Branch protection: Bật required checks cho PR
-
Timeout: Thêm
timeout-minutes: 10tránh workflow chạy mãi
CI/CD setup của bạn trông như thế nào? Share workflow hay nhé!
Top comments (0)