---
title: "Tự động hóa deploy Python FastAPI lên Cloud VPS bằng GitHub Actions"
description: "Hướng dẫn thiết lập pipeline CI/CD tự động build Docker và deploy Python FastAPI lên Cloud VPS bằng GitHub Actions, zero-downtime và an toàn SSH."
canonical: "https://thuecloud.vn/tu-dong-hoa-deploy-python-fastapi-len-cloud-vps-bang-github-actions"
markdown_url: "https://thuecloud.vn/tu-dong-hoa-deploy-python-fastapi-len-cloud-vps-bang-github-actions.md"
locale: "vi"
kind: "article"
published_at: "2026-11-22T16:18:17.821Z"
updated_at: "2026-11-22T16:18:15.649Z"
site: "ThueCloud.Vn"
estimated_tokens: 1934
---
# Tự động hóa deploy Python FastAPI lên Cloud VPS bằng GitHub Actions

> Hướng dẫn thiết lập pipeline CI/CD tự động build Docker và deploy Python FastAPI lên Cloud VPS bằng GitHub Actions, zero-downtime và an toàn SSH.

- Canonical HTML: https://thuecloud.vn/tu-dong-hoa-deploy-python-fastapi-len-cloud-vps-bang-github-actions
- Markdown URL: https://thuecloud.vn/tu-dong-hoa-deploy-python-fastapi-len-cloud-vps-bang-github-actions.md
- Organization: ThueCloud.Vn
- Support Email: support@thuecloud.vn
- Hotline: 03333 499 48
- Published: 2026-11-22
- Updated: 2026-11-22

## Mục lục

- Chuẩn bị Dockerfile và Docker Compose cho FastAPI
  - Bảng kiểm tra (Checklist) chuẩn bị VPS trước khi chạy CI/CD
- Cấu hình Workflow GitHub Actions
- Câu hỏi thường gặp (FAQ)
  - Nên build Docker image trên GitHub Actions hay build trực tiếp trên VPS?
  - Làm sao cấp quyền cho GitHub Actions pull image từ GHCR mà không lộ mật khẩu?
  - Khi docker compose up -d chạy lại có bị rớt request đang xử lý không?

Triển khai thủ công bằng cách SSH vào server rồi chạy `git pull` rất dễ gây gián đoạn dịch vụ hoặc sai lệch thư viện Python. Với một pipeline GitHub Actions gọn nhẹ kết hợp Docker Compose trên [Cloud VPS Việt Nam](https://thuecloud.vn/vps-viet-nam), mỗi lần push code lên nhánh `main` sẽ tự động build, kiểm tra healthcheck và cập nhật ứng dụng FastAPI không downtime.

> **Tóm tắt nhanh (TL;DR):**
> - **Đóng gói Multi-stage Docker:** Dùng `python:3.12-slim` và `uvicorn`/`gunicorn` giúp image nhẹ dưới 180MB.
> - **Bảo mật kết nối:** Sử dụng SSH Deploy Key riêng và GitHub Secrets thay vì lưu mật khẩu root.
> - **Healthcheck trước khi switch:** Đảm bảo container mới trả về `200 OK` tại `/health` trước khi gỡ container cũ.
> - *Cập nhật: 11/2026*

## Chuẩn bị Dockerfile và Docker Compose cho FastAPI

Để tối ưu tốc độ build và khả năng chịu tải trên VPS, hãy sử dụng multi-stage build và chạy `fastapi` qua `gunicorn` với `uvicorn.workers.UvicornWorker`:

```dockerfile
FROM python:3.12-slim AS builder
WORKDIR /app
COPY requirements.txt .
RUN pip wheel --no-cache-dir --no-deps --wheel-dir /app/wheels -r requirements.txt

FROM python:3.12-slim
WORKDIR /app
COPY --from=builder /app/wheels /wheels
RUN pip install --no-cache /wheels/*
COPY . .
EXPOSE 8000
CMD ["gunicorn", "app.main:app", "-w", "4", "-k", "uvicorn.workers.UvicornWorker", "-b", "0.0.0.0:8000"]
```

Số lượng worker (`-w`) nên đặt theo công thức `(2 × số_vCPU) + 1` dựa trên gói bạn chọn tại [bảng giá Cloud VPS](https://thuecloud.vn/pricing).

### Bảng kiểm tra (Checklist) chuẩn bị VPS trước khi chạy CI/CD

| Hạng mục | Yêu cầu cấu hình | Lệnh kiểm tra trên VPS |
| :--- | :--- | :--- |
| Docker & Compose | Docker Engine 24+ & Compose v2 | `docker compose version` |
| User deploy riêng | Không dùng `root`, thuộc group `docker` | `id deploy && groups deploy` |
| Firewall UFW | Chỉ mở port 22, 80, 443 | `sudo ufw status` |
| Swap bảo vệ OOM | Tối thiểu 2GB swap trên NVMe | `swapon --show` |

## Cấu hình Workflow GitHub Actions

Tạo file `.github/workflows/deploy.yml` trong repository. Quy trình sẽ build image, đẩy lên GitHub Container Registry (`ghcr.io`), sau đó SSH vào VPS để pull và khởi động lại:

```yaml
name: Deploy FastAPI to VPS
on:
  push:
    branches: ["main"]
jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}
      - uses: docker/build-push-action@v5
        with:
          push: true
          tags: ghcr.io/${{ github.repository }}:latest
      - name: Deploy via SSH
        uses: appleboy/ssh-action@v1.0.3
        with:
          host: ${{ secrets.VPS_HOST }}
          username: ${{ secrets.VPS_USER }}
          key: ${{ secrets.VPS_SSH_KEY }}
          script: |
            cd /opt/fastapi-app
            docker compose pull
            docker compose up -d --remove-orphans
            docker image prune -f
```

Nếu ứng dụng FastAPI của bạn kết nối cơ sở dữ liệu quan hệ, đừng bỏ qua bài [phân tích kỹ thuật MVCC trong PostgreSQL vs MySQL InnoDB](https://thuecloud.vn/phan-tich-ky-thuat-mvcc-trong-postgresql-vs-mysql-innodb-khi-nao-nen-dung-trong-thuc-te). Trường hợp bạn triển khai cho AI workflow hoặc vector search, xem thêm [thiết lập sao lưu tự động cho Qdrant AI RAG](https://thuecloud.vn/thiet-lap-sao-luu-tu-dong-va-khoi-phuc-nhanh-cho-qdrant-ai-rag) hoặc [so sánh n8n self-hosted vs Make.com](https://thuecloud.vn/so-sanh-n8n-self-hosted-vs-make-com-2026-hieu-nang-chi-phi-va-kich-ban-nen-chon) trong danh mục [giải pháp hạ tầng](https://thuecloud.vn/giai-phap).

> **Chạy CI/CD và API FastAPI mượt mà tại ThueCloud.Vn:**
> Hạ tầng **KVM Enterprise NVMe** tại `vn-hn`, băng thông ổn định giúp pull Docker image chỉ trong vài giây. Cam kết **VAT 0%**, **SLA 99,9%**, hoàn tiền **07 ngày**:
> - **VPS VN 1:** `45.000đ` (năm) / `60.000đ/tháng` — Phù hợp microservice nhỏ.
> - **VPS VN 2:** `78.000đ` (năm) / `90.000đ/tháng` — Chạy tốt FastAPI + PostgreSQL.
> - **VPS VN 3:** `139.000đ` (năm) / `170.000đ/tháng` — Dư giả cho 4 workers + Redis.

## Câu hỏi thường gặp (FAQ)

### Nên build Docker image trên GitHub Actions hay build trực tiếp trên VPS?
Nên build trên GitHub Actions (hoặc GitLab Runner) rồi push lên registry để tránh làm tăng CPU và đầy RAM trên VPS production trong lúc người dùng đang truy cập.

### Làm sao cấp quyền cho GitHub Actions pull image từ GHCR mà không lộ mật khẩu?
Trên VPS, bạn tạo một Personal Access Token (PAT) chỉ có quyền `read:packages` và chạy lệnh `docker login ghcr.io` một lần duy nhất với user `deploy`.

### Khi `docker compose up -d` chạy lại có bị rớt request đang xử lý không?
Mặc định Docker gửi tín hiệu `SIGTERM` và chờ 10 giây (`stop_grace_period`) để Uvicorn/Gunicorn hoàn tất các request đang mở. Bạn có thể kết hợp Traefik hoặc Caddy với healthcheck để đạt zero-downtime thực sự.

## References / Sources

- https://fastapi.tiangolo.com/deployment/docker/
- https://docs.github.com/en/actions/writing-workflows

---

## Navigation & Machine-Readable Endpoints

- [Site Summary (llms.txt)](https://thuecloud.vn/llms.txt)
- [Full Technical Reference (llms-full.txt)](https://thuecloud.vn/llms-full.txt)
- [Pricing Catalog (Markdown)](https://thuecloud.vn/pricing.md)
- [Blog & Technical Guides (Markdown)](https://thuecloud.vn/blog.md)
- [XML Sitemap](https://thuecloud.vn/sitemap.xml)
