🎯 Mục tiêu bài học
AI applications có những yêu cầu đặc biệt: GPU access, model weights, lớn RAM. Bài này cover các patterns Docker đặc thù cho AI.
Sau bài này, bạn sẽ:
✅ Hiểu các challenges khi Dockerize AI applications ✅ Cấu hình GPU support với NVIDIA Docker ✅ Implement model caching strategy ✅ Build optimized Dockerfile cho AI apps ✅ Quản lý secrets và resource limits
🔍 AI Docker Challenges
Checkpoint
Bạn đã nắm được các challenges đặc thù khi Dockerize AI apps chưa?
🛠️ GPU Support với NVIDIA Docker
1# GPU-enabled base image2FROM nvidia/cuda:12.1.0-runtime-ubuntu22.043 4# Install Python5RUN apt-get update && \6 apt-get install -y python3.11 python3-pip && \7 rm -rf /var/lib/apt/lists/*8 9WORKDIR /app10COPY requirements.txt .11RUN pip install --no-cache-dir -r requirements.txt12 13COPY . .14CMD ["python3", "main.py"]1# Run with GPU2docker run --gpus all -p 8000:8000 ai-gpu-app:latest3 4# Specific GPU5docker run --gpus '"device=0"' -p 8000:8000 ai-gpu-app:latestCheckpoint
Bạn đã hiểu cách cấu hình GPU access cho Docker containers chưa?
⚡ Model Caching Strategy
1FROM python:3.11-slim2 3WORKDIR /app4 5# Install deps6COPY requirements.txt .7RUN pip install --no-cache-dir -r requirements.txt8 9# Pre-download models (cached in image)10RUN python -c "from transformers import AutoModel; AutoModel.from_pretrained('sentence-transformers/all-MiniLM-L6-v2')"11 12COPY . .13CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]1# Or mount model cache volume2docker run -d \3 -v model-cache:/root/.cache/huggingface \4 -p 8000:8000 \5 ai-app:latestCheckpoint
Bạn đã hiểu cách cache model weights trong Docker image hoặc volume chưa?
💻 Optimized AI Dockerfile
1# Optimized for AI API (no local models)2FROM python:3.11-slim AS production3 4WORKDIR /app5 6# System deps7RUN apt-get update && apt-get install -y \8 curl \9 && rm -rf /var/lib/apt/lists/*10 11# Python deps12COPY requirements.txt .13RUN pip install --no-cache-dir -r requirements.txt14 15# App code16COPY app/ ./app/17 18# Security19RUN useradd -m -r appuser20USER appuser21 22# Config23ENV PYTHONUNBUFFERED=124ENV PYTHONDONTWRITEBYTECODE=125 26EXPOSE 800027HEALTHCHECK --interval=30s --timeout=10s \28 CMD curl -f http://localhost:8000/health || exit 129 30CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "2"]Checkpoint
Bạn đã hiểu cách tối ưu Dockerfile cho AI API production chưa?
🔒 Docker Secrets
1# Never put API keys in Dockerfile!2# Use secrets at runtime3 4# Method 1: Environment variables5docker run -e OPENAI_API_KEY=sk-xxx ai-app6 7# Method 2: Secret file8echo "sk-xxx" | docker secret create openai_key -9 10# Method 3: Docker Compose secrets11# See next lessonCheckpoint
Bạn đã hiểu cách quản lý API keys an toàn với Docker chưa?
📐 Resource Limits
1# Limit memory and CPU2docker run -d \3 --memory=2g \4 --cpus=2 \5 --name ai-api \6 -p 8000:8000 \7 ai-app:latestCheckpoint
Bạn đã hiểu cách giới hạn tài nguyên cho Docker containers chưa?
🛠️ Health Check Pattern
1# app/main.py2from fastapi import FastAPI3from langchain_openai import ChatOpenAI45app = FastAPI()67@app.get("/health")8async def health():9 return {"status": "healthy"}1011@app.get("/ready")12async def readiness():13 try:14 llm = ChatOpenAI(model="gpt-4o-mini")15 response = await llm.ainvoke("test")16 return {"status": "ready", "llm": "connected"}17 except Exception as e:18 return {"status": "not_ready", "error": str(e)}Checkpoint
Bạn đã hiểu sự khác biệt giữa health check và readiness check chưa?
⚡ Image Size Optimization
1# Compare sizes2docker images3# python:3.11 -> ~1GB4# python:3.11-slim -> ~150MB5# python:3.11-alpine -> ~50MB (may have issues with some packages)6 7# Tips to reduce size:8# 1. Use slim base images9# 2. Multi-stage builds10# 3. Clean apt cache11# 4. Use --no-cache-dir for pip12# 5. Remove unnecessary filesCheckpoint
Bạn đã biết cách chọn base image và tối ưu image size chưa?
🎯 Tổng kết
Bài tập thực hành
- Build optimized Docker image cho AI API
- Implement health check endpoints
- Setup resource limits
- Compare image sizes giữa các base images
Target: Production-ready Docker image dưới 300MB
Câu hỏi tự kiểm tra
- Khi Dockerize AI application, cần quản lý environment variables (API keys) như thế nào để đảm bảo security?
- Health check endpoint và readiness endpoint khác nhau như thế nào trong context của AI Docker containers?
- So sánh image sizes giữa python:3.11, python:3.11-slim và python:3.11-alpine — khi nào nên dùng loại nào?
- Resource limits (memory, CPU) cần được cấu hình như thế nào cho Docker containers chạy AI workloads?
🎉 Tuyệt vời! Bạn đã hoàn thành bài học Docker cho AI Apps!
Tiếp theo: Chúng ta sẽ học Docker Compose để orchestrate multi-service AI deployments.
