📑 Mục lục bài viết
Quy trình Tích hợp Liên tục và Triển khai Liên tục (Continuous Integration / Continuous Deployment – CI/CD) là xương sống của mọi đội ngũ phát triển phần mềm Agile. Việc tự động hóa toàn bộ quá trình kiểm thử, đóng gói Docker Image và deploy lên máy chủ giúp loại bỏ 99% lỗi do thao tác thủ công.
1. Cấu trúc một Pipeline CI/CD Tiêu chuẩn
- Lint & Type Check: Kiểm tra định dạng code và kiểm tra kiểu dữ liệu tĩnh.
- Unit & Integration Test: Tự động chạy toàn bộ bài kiểm thử tự động, đảm bảo tính năng mới không làm hỏng logic cũ.
- Docker Build & Push: Đóng gói ứng dụng thành Docker Image và đẩy lên Docker Hub hoặc GitHub Container Registry (GHCR).
- Deploy (SSH/Webhook): Kích hoạt máy chủ production tải image mới và restart container không gián đoạn (Zero-Downtime Deployment).
2. File Cấu hình GitHub Actions Workflow Hoàn chỉnh
Tạo file .github/workflows/deploy.yml trong repository:
name: Production CI/CD Pipeline
on:
push:
branches: [ "main" ]
jobs:
build-and-deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout Source Code
uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Log in to GitHub Container Registry
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Build and Push Docker Image
uses: docker/build-push-action@v5
with:
context: .
push: true
tags: ghcr.io/${{ github.repository }}:latest
cache-from: type=gha
cache-to: type=gha,mode=max
- name: Deploy to Remote Server via SSH
uses: appleboy/[email protected]
with:
host: ${{ secrets.SERVER_HOST }}
username: ${{ secrets.SERVER_USER }}
key: ${{ secrets.SERVER_SSH_KEY }}
script: |
docker pull ghcr.io/${{ github.repository }}:latest
docker compose down
docker compose up -d --remove-orphans
3. Quản lý Secrets và Bảo mật Pipeline
Tuyệt đối không lưu mật khẩu, SSH key hay API token trực tiếp trong git. Luôn sử dụng GitHub Encrypted Secrets và cấp quyền tối thiểu (Least Privilege) cho các Service Account kết nối vào hệ thống.
Leave a Reply