Cách mình setup CI/CD đơn giản với GitHub Actions
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
```yaml
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
```yaml
- 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)
```yaml
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
1. **Secrets**: Đặt ở repo Settings → Secrets, KHÔNG hardcode trong workflow
2. **`npm ci`** thay `npm install`: nhanh hơn, deterministic
3. **`needs: test`**: Deploy chỉ chạy khi test pass
4. **Branch protection**: Bật required checks cho PR
5. **Timeout**: Thêm `timeout-minutes: 10` tránh workflow chạy mãi
---
CI/CD setup của bạn trông như thế nào? Share workflow hay nhé!
All rights reserved