Mỗi lần deploy thủ công là một lần có thể quên bước nào đó, push code thiếu, hoặc deploy nhầm branch. CI/CD giải quyết tất cả điều này bằng cách tự động hóa toàn bộ pipeline.
GitHub Actions Là Gì?
GitHub Actions là nền tảng CI/CD tích hợp sẵn trong GitHub. Bạn định nghĩa workflows bằng YAML, và GitHub tự chạy trên máy chủ của họ khi có event (push, PR, schedule).
- Free: 2000 phút/tháng cho public repos (vô hạn), private repos có quota
- Marketplace: Hàng nghìn action có sẵn từ cộng đồng
- Matrix builds: Test trên nhiều OS/version cùng lúc
Workflow Đầu Tiên — Chạy Test
# .github/workflows/test.yml
name: Run Tests
on:
push:
branches: [main, develop]
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:16
env:
POSTGRES_DB: testdb
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
steps:
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.12'
cache: 'pip'
- name: Install dependencies
run: pip install -r requirements.txt
- name: Run tests
env:
DATABASE_URL: postgres://postgres:postgres@localhost/testdb
run: python manage.py test
Build Và Push Docker Image
build:
needs: test
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Log in to Docker Hub
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Build and push
uses: docker/build-push-action@v5
with:
push: true
tags: username/blog:${{ github.sha }},username/blog:latest
Deploy Lên Server Qua SSH
deploy:
needs: build
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/main'
steps:
- name: Deploy via SSH
uses: appleboy/ssh-action@v1
with:
host: ${{ secrets.SERVER_HOST }}
username: ${{ secrets.SERVER_USER }}
key: ${{ secrets.SSH_PRIVATE_KEY }}
script: |
cd /app
docker pull username/blog:latest
docker-compose up -d --force-recreate web
docker system prune -f
Secrets Và Environment Variables
Vào Settings → Secrets and variables → Actions để thêm secrets. Không bao giờ hardcode credentials trong YAML file.
# Dùng secrets trong workflow
env:
SECRET_KEY: ${{ secrets.DJANGO_SECRET_KEY }}
DATABASE_URL: ${{ secrets.DATABASE_URL }}
Matrix Builds — Test Nhiều Version
jobs:
test:
strategy:
matrix:
python-version: ['3.11', '3.12']
os: [ubuntu-latest, windows-latest]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
CI/CD không phải là luxury cho team lớn — nó là safety net cho bất kỳ project nào. Lần đầu setup tốn 2 giờ, nhưng tiết kiệm hàng trăm giờ sau đó.
Kết Luận
Bắt đầu với workflow đơn giản: checkout → install deps → run tests. Khi đã quen, thêm dần build và deploy. Đừng cố làm tất cả trong một lần — CI/CD tốt được xây dựng dần theo nhu cầu thực tế.
Chưa có bình luận. Hãy là người đầu tiên!