ONE is preparing: 01 / INITIALIZING MODEL ROUTER. Evaluating routing across providers.
Current state
01 / INITIALIZING MODEL ROUTER.

Evaluating routing across providers.

Start learning
← Hạ tầng & Vận hành

AI Builder

Container hoá — Đóng gói AI gọn gàng

Vietnamese onlyThe learning content is available in Vietnamese only. The surrounding interface follows your language.

Kỹ thuật đóng gói mô hình AI cùng mọi phụ thuộc vào container, đảm bảo chạy nhất quán trên mọi môi trường.

lesson120 minHạ tầng & Vận hànhAI Engineer

Giới thiệu

Team train model trên Ubuntu 22.04 + CUDA 12.1 + PyTorch 2.1. Deploy lên server Ubuntu 20.04 + CUDA 11.8 → crash. Nguyên nhân gốc rễ?

'Works on my machine' là kinh điển. Container đóng gói Python + PyTorch + CUDA + model vào một hộp chuẩn → chạy giống nhau trên mọi máy có kernel tương thích.

Container hoá là kỹ thuật đóng gói ứng dụng cùng mọi phụ thuộc vào một đơn vị chuẩn. Bài này đi qua vòng đời: Dockerfile → Image → Container → Network → Orchestration , so VM với container, và mô phỏng Kubernetes thật.

Vòng đời container

Từ Dockerfile đến container đang chạy

1 / 5
  1. 1. Dockerfile

    Bản thiết kế khai báo từng bước build.

Khoảnh khắc Aha

Container chia sẻ kernel với host (không boot OS riêng) → khởi động trong vài giây thay vì vài phút. Overhead chỉ 1–3% (VM: 15–20%). Chính vì thế 90% workload AI production hiện chạy trên Docker + Kubernetes: nhẹ như app, cô lập như VM.

VM vs Container

Điểm khác biệt cốt lõi: VM boot OS riêng (Guest OS) trong mỗi hộp → hàng GB RAM và 30–60s khởi động. Container chia sẻ kernel host → chỉ cần process namespace → MB và 1–5s.

Container khởi động nhanh hơn VM vì lý do nào?

Thử thách 1

Docker image cho model AI thường rất lớn (5–15GB) vì chứa CUDA, PyTorch, model weights. Cách nào giảm kích thước hiệu quả nhất?

Multi-stage build: stage 1 cài pip packages (cần compiler, headers), stage 2 base nhỏ gọn + copy chỉ packages đã build. Giảm image 2–3×. Kết hợp .dockerignore loại file thừa.

Thử thách 2

Mô hình load weights 12GB vào VRAM mỗi lần container khởi động. Cách làm nào giảm cold-start hiệu quả?

Để weights trong ReadOnlyMany volume (đã warm cache filesystem), đặt minReplicas ≥ 1 để luôn có pod sẵn sàng, dùng readiness probe để K8s không route traffic vào pod đang load.

Container vs VM

Container hoá là kỹ thuật đóng gói ứng dụng (model AI + code + dependencies) vào một đơn vị chuẩn chạy nhất quán trên mọi môi trường. Đây là nền tảng của MLOps hiện đại và hỗ trợ model serving đa môi trường.

Công thức khái niệm — Container vs VM:

VM=App+Guest OS+Hypervisor (startup: phuˊt, overhead: 15-20%)\text{VM} = \text{App} + \text{Guest OS} + \text{Hypervisor} \ (\text{startup: phút, overhead: 15-20\%})
Container=App+Libs (share host kernel, startup: giaˆy, overhead: 1-3%)\text{Container} = \text{App} + \text{Libs} \ (\text{share host kernel, startup: giây, overhead: 1-3\%})

Vòng đời Docker

Vòng đời Docker:

  1. Dockerfile — bản thiết kế khai báo từng bước build.
  2. Image — kết quả build, bất biến, có thể push lên registry.
  3. Container — instance runtime của image với namespace riêng.
  4. Network / Volume — kết nối với nhau và với storage bền vững.
  5. Orchestration — Kubernetes/Nomad quản lý ở quy mô cluster.

Docker cho AI workflow

Docker cho AI workflow:

  • Reproducibility: Dockerfile là bản thiết kế chính xác, ai build cũng ra image giống.
  • Isolation: Model A dùng PyTorch 2.0, Model B dùng 2.3 — không xung đột vì mỗi container có libs riêng.
  • Portability: Build trên laptop, chạy trên FPT Cloud/AWS/GCP — giống hệt.
  • Scaling: Kubernetes tạo 100 replica từ 1 image chỉ trong vài giây.

Dockerfile tối ưu cho AI model serving

# ── Stage 1: Build dependencies ───────────────────────────
FROM python:3.11-slim AS builder
WORKDIR /build

# System deps cần để compile một số wheel
RUN apt-get update && apt-get install -y --no-install-recommends \
        build-essential git && \
    rm -rf /var/lib/apt/lists/*

COPY requirements.txt .
RUN pip install --no-cache-dir --prefix=/install -r requirements.txt

# ── Stage 2: Runtime (nhỏ gọn, CUDA đầy đủ) ───────────────
FROM nvidia/cuda:12.1.0-runtime-ubuntu22.04
WORKDIR /app

# Tạo user không phải root để tăng bảo mật
RUN useradd -m -u 1000 appuser

# Copy Python từ builder, chỉ những package đã cài
COPY --from=builder /install /usr/local
COPY --chown=appuser:appuser ./src /app/src
COPY --chown=appuser:appuser ./model /app/model

# Config qua env vars (12-Factor)
ENV MODEL_PATH=/app/model/llama-7b-q4.gguf \
    CUDA_VISIBLE_DEVICES=0 \
    PYTHONUNBUFFERED=1 \
    PORT=8000

# Healthcheck để K8s biết pod sẵn sàng
HEALTHCHECK --interval=30s --timeout=5s --start-period=60s \
    CMD curl -fsS http://localhost:${PORT}/healthz || exit 1

USER appuser
EXPOSE 8000
CMD ["uvicorn", "src.server:app", "--host", "0.0.0.0", "--port", "8000"]
# Image: ~5.2GB (so với ~15GB nếu single-stage)

Kubernetes Deployment + HPA với GPU

apiVersion: apps/v1
kind: Deployment
metadata:
  name: ml-api
  labels: { app: ml-api }
spec:
  replicas: 3                # baseline 3 bản sao
  selector:
    matchLabels: { app: ml-api }
  strategy:
    type: RollingUpdate
    rollingUpdate: { maxSurge: 1, maxUnavailable: 0 }
  template:
    metadata:
      labels: { app: ml-api }
    spec:
      containers:
      - name: serving
        image: registry.fpt.cloud/ai-team/ml-api:v2.1
        ports:
        - containerPort: 8000
        env:
        - name: MODEL_PATH
          value: /models/llama-7b-q4.gguf
        resources:
          limits:
            nvidia.com/gpu: 1
            memory: "16Gi"
            cpu: "4"
          requests:
            memory: "8Gi"
            cpu: "2"
        readinessProbe:
          httpGet: { path: /healthz, port: 8000 }
          initialDelaySeconds: 30
          periodSeconds: 10
        livenessProbe:
          httpGet: { path: /livez, port: 8000 }
          initialDelaySeconds: 60
        volumeMounts:
        - name: model-cache
          mountPath: /models
          readOnly: true
      volumes:
      - name: model-cache
        persistentVolumeClaim: { claimName: model-pvc }
---
apiVersion: v1
kind: Service
metadata: { name: ml-api }
spec:
  selector: { app: ml-api }
  ports:
  - port: 80
    targetPort: 8000
  type: ClusterIP
---
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata: { name: ml-api-hpa }
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: ml-api
  minReplicas: 2
  maxReplicas: 10
  metrics:
  - type: Resource
    resource:
      name: nvidia.com/gpu
      target:
        type: Utilization
        averageUtilization: 70

Namespaces và layer caching

Linux cung cấp namespaces (PID, NET, MNT, USER, UTS, IPC) tạo ảo giác mỗi container có hệ thống riêng: danh sách process, card mạng, filesystem, users… Đồng thời cgroups (control groups) giới hạn CPU, RAM, I/O. Container = process chạy trên kernel host nhưng được "nhìn" qua lăng kính namespaces và bị giới hạn bởi cgroups — không phải máy ảo, không có hypervisor.

Mỗi lệnh trong Dockerfile tạo một layer; Docker cache layer theo hash của lệnh + nội dung file liên quan. Nếu đặt COPY ./src trước RUN pip install, mỗi lần sửa code sẽ invalidate cache pip → build lại toàn bộ. Thứ tự chuẩn: hiếm thay đổi trước, hay thay đổi sau — requirements.txt trước, src/ sau. Tiết kiệm 5–15 phút mỗi lần build.

Container hoá không phải "viên đạn bạc": cần đầu tư vào image scanning, registry auth, secrets management, log aggregation. Nhưng một khi có nền tảng, đó là bệ phóng cho mọi MLOps và model serving ở quy mô.

Tóm tắt

  • Container đóng gói model + dependencies vào 'hộp' chuẩn — chạy giống nhau trên mọi máy có kernel tương thích.
  • Nhẹ hơn VM vì chia sẻ kernel (1–3% overhead); khởi động trong vài giây thay vì phút.
  • Dockerfile là bản thiết kế; Image là kết quả build bất biến; Container là instance runtime có namespace riêng.
  • NVIDIA Container Toolkit cho phép container truy cập GPU mà không cần cài CUDA driver riêng.
  • Multi-stage build + .dockerignore + tách model weights ra volume giảm image 2–3× và cold-start đáng kể.
  • Kubernetes điều phối cluster: Pod là đơn vị deploy, Deployment giữ N replicas, HPA auto-scale, Service cân bằng tải.

Continue the module

Lesson 4 of 9