(BÀI 8): Deployment & CI/CD với GitHub Actions

Giới thiệu tổng quan về Deployment & CI/CD trong Python

Trong thực tế, viết code chỉ là một phần nhỏ của vòng đời dự án. Điều quan trọng hơn là:

  • Làm sao để triển khai (deploy) code mới nhanh và chính xác?

  • Làm sao để kiểm thử tự động (auto test) trước khi triển khai?

  • Làm sao để cập nhật version, build package, tạo release, chạy test, publish… hoàn toàn tự động?

Đây là nhiệm vụ của CI/CD (Continuous Integration – Continuous Deployment).

Và trong Python, công cụ đơn giản – dễ dùng – miễn phí – mạnh nhất chính là:

GitHub Actions.


CI/CD là gì?

CI (Continuous Integration)
Tự động kiểm tra (test), phân tích (lint), build mỗi lần bạn push code lên GitHub.

CD (Continuous Delivery / Continuous Deployment)

  • Delivery: chuẩn bị bản build để deploy.

  • Deployment: tự động deploy lên server/hosting/PyPI.

CI/CD đảm bảo:

  • Commit nào lỗi → biết ngay

  • Không bao giờ deploy code hỏng

  • Tự động hoá toàn bộ quy trình phát hành

  • Làm việc nhóm hiệu quả hơn

  • Hạn chế thao tác thủ công dễ sai sót


GitHub Actions – cách hoạt động

GitHub Actions dùng workflow dạng YAML nằm trong folder:

.github/workflows/

Mỗi workflow là một pipeline gồm:

  • trigger (khi nào chạy: push, PR, schedule)

  • jobs (các khối công việc song song hoặc nối tiếp)

  • steps (từng bước trong job)

  • actions (task chạy sẵn như checkout code, setup Python, upload artifact)

Workflow chạy trên machine ảo:

  • ubuntu-latest

  • windows-latest

  • macos-latest


Tạo workflow CI cơ bản: Test Python bằng pytest

Tạo file:

.github/workflows/ci.yml

Nội dung:

name: Python CI
on:

push:
branches: [“main”]
pull_request:
branches: [“main”]

jobs:
build:
runs-on: ubuntu-latest

steps:
name: Checkout code
uses: actions/checkout@v4

name: Set up Python
uses: actions/setup-python@v5
with:
python-version: “3.11”

name: Install dependencies
run: |
python -m pip install –upgrade pip
pip install -r requirements.txt
pip install pytest

name: Run tests
run: |
pytest -q

Diễn giải từng phần

  • on:
    Chạy khi push hoặc tạo Pull Request vào nhánh main.

  • actions/checkout@v4
    Tải mã nguồn về runner.

  • actions/setup-python
    Cài Python version bạn cần.

  • pip install -r requirements.txt
    Cài các thư viện bạn định dùng.

  • pytest
    Chạy test tự động.

Kết quả: mỗi lần push lên GitHub → test tự chạy → báo xanh/đỏ.


Thêm lint & formatting (black, flake8)

Cập nhật file workflow:

- name: Install format/lint tools
run: |
pip install black flake8

- name: Run black
run: black --check .
name: Run flake8
run: flake8 .

Giúp kiểm soát chất lượng code tự động.


Build package Python và tạo artifact

Nếu bạn có package Python (như bài trước), dùng:

- name: Build package
run: |
pip install build
python -m build

- name: Upload build artifact
uses: actions/upload-artifact@v4
with:
name: dist-files
path: dist/*

Sau khi workflow chạy → bản build dist/*.whl tự động được upload để download.


Publish package lên PyPI tự động

Đầu tiên cần tạo API token từ PyPI
→ Tạo secret trong GitHub repo:

Settings → Secrets → Actions → New repository secret

  • Name: PYPI_TOKEN

  • Value: token từ PyPI

Workflow publish:

name: Publish to PyPI

on:
push:
tags:
“v*.*.*”

jobs:
deploy:
runs-on: ubuntu-latest

steps:
uses: actions/checkout@v4

uses: actions/setup-python@v5
with:
python-version: “3.11”

name: Install build tools
run: pip install build twine

name: Build
run: python -m build

name: Publish
run: twine upload dist/* -u __token__ -p ${{ secrets.PYPI_TOKEN }}

Giải thích

  • Workflow chạy khi bạn push tag: v1.0.0, v0.2.1

  • Tự động build gói .whl và upload lên PyPI.


Tạo release tự động trên GitHub

Workflow:

name: Auto Release

on:
push:
tags:
“v*.*.*”

jobs:
release:
runs-on: ubuntu-latest

steps:
uses: actions/checkout@v4

name: Create Release
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ github.ref_name }}

Khi push tag → GitHub tạo release page tự động.


Triển khai Web App Python (Flask/FastAPI) lên server Linux (SSH deploy)

Dạng auto-deploy phổ biến:

  • Bạn thuê VPS / server Linux

  • Code lưu trên GitHub

  • Mỗi lần push → GitHub Actions SSH vào server và pull code mới

Workflow:

name: Deploy to Server

on:
push:
branches: [“main”]

jobs:
deploy:
runs-on: ubuntu-latest

steps:
uses: actions/checkout@v4

name: Deploy via SSH
uses: appleboy/ssh-action@v1.1.0
with:
host: ${{ secrets.SERVER_IP }}
username: ${{ secrets.SERVER_USER }}
key: ${{ secrets.SERVER_SSH_KEY }}
script: |
cd /var/www/myapp
git pull origin main
source venv/bin/activate
pip install -r requirements.txt
systemctl restart myapp

Giải thích

  • appleboy/ssh-action cho phép chạy lệnh từ xa

  • Server chạy Flask/FastAPI dùng systemd

  • Mỗi lần push: code tự cập nhật → dịch vụ tự restart


Triển khai Python Web lên Docker + GitHub Actions

Bạn có thể build Docker image trong workflow.

- name: Login to DockerHub
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKER_USER }}
password: ${{ secrets.DOCKER_PASS }}
name: Build and push Docker image
uses: docker/build-push-action@v5
with:
context: .
push: true
tags: yourname/app:latest

Diễn giải

  • GitHub Actions build image từ code mới

  • Push lên DockerHub

  • Server chỉ cần pull lại và restart container


Triển khai Python Web lên Render / Railway / Deta / HuggingFace

Dùng GitHub Actions để:

  • Trigger deploy

  • Upload artifact

  • Update environment

  • Refresh service

Ví dụ với Render:

- name: Deploy Render Service
uses: JorgeLNJunior/render-deploy@v1
with:
serviceId: ${{ secrets.RENDER_SERVICE_ID }}
apiKey: ${{ secrets.RENDER_API_KEY }}

Cron job bằng GitHub Actions (schedule)

Chạy tự động theo lịch (hàng ngày/giờ):

on:
schedule:
- cron: "0 * * * *" # mỗi giờ

Dùng để:

  • Auto backup

  • Auto generate report

  • Auto crawl dữ liệu

  • Auto gửi email


Best Practices khi dùng GitHub Actions

1. Luôn dùng venv/requirements.txt hoặc poetry

Để build tái sử dụng được.

2. Dùng actions/cache để tăng tốc

Cache pip:

- name: Cache pip
uses: actions/cache@v4
with:
path: ~/.cache/pip
key: ${{ runner.os }}-pip-${{ hashFiles('**/requirements.txt') }}

3. Không commit secret lên repo

Dùng GitHub Secrets.

4. Không chạy deploy trên nhánh dev

Chỉ chạy trên:

main
release/*
tag: v*.*.*

5. Tách CI và CD thành 2 workflow

CI chạy test
CD triển khai

6. Không đưa password, token vào log

Dùng *** mask hoặc GitHub secrets.

7. Dùng matrix build để test nhiều version Python

Ví dụ:

strategy:
matrix:
python-version: ["3.9", "3.10", "3.11"]

Kết bài

Deployment & CI/CD là một phần thiết yếu của bất kỳ dự án Python chuyên nghiệp nào. GitHub Actions giúp bạn:

  • Tự động hoá test

  • Build package

  • Deploy lên server/hosting

  • Publish PyPI

  • Tạo release

  • Quản lý Docker

  • Chạy workflow theo lịch

Một lập trình viên chuyên nghiệp luôn dùng CI/CD, vì nó giảm rủi ro, tăng tốc độ phát triển và đảm bảo chất lượng phần mềm.

Tiếp tục chuỗi series tự học python: (Bài 9): Lập trình hướng đối tượng

1 Trackback / Pingback

  1. (Bài 7): Module và thư viện trong python - aidanang.com

Leave a Reply

Your email address will not be published.


*