02. Serving: FastAPI & Docker
개요
노트북은 개발에 좋지만, 프로덕션에는 서버가 필요합니다. 에이전트 로직을 감싸는 FastAPI 템플릿과 컨테이너화하는 Docker 사용법을 제공합니다.
핵심 개념
| 개념 | 설명 |
|---|---|
| FastAPI | Python으로 API를 구축하는 모던하고 빠른 웹 프레임워크 |
| Docker | 컨테이너라는 패키지로 소프트웨어를 제공하는 플랫폼 |
| Health Check | 서비스가 올바르게 실행 중인지 확인하는 엔드포인트 |
| Pydantic | 데이터 검증 및 설정 관리 |
프로젝트 구조
serving_api/
├── main.py # FastAPI 애플리케이션
├── Dockerfile # 컨테이너 정의
├── requirements.txt # 의존성
└── .env.example # 환경 변수 템플릿FastAPI 기본 구조
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI(title="Agent API")
class Query(BaseModel):
question: str
context: str | None = None
class Response(BaseModel):
answer: str
sources: list[str] = []
@app.get("/health")
async def health_check():
return {"status": "healthy"}
@app.post("/ask", response_model=Response)
async def ask_agent(query: Query):
# 에이전트 로직 호출
result = agent.run(query.question)
return Response(answer=result)Docker 컨테이너화
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]실행 방법
로컬 개발
cd week4_production/serving_api
pip install -r requirements.txt
uvicorn main:app --reloadDocker 빌드 및 실행
docker build -t agent-api .
docker run -p 8000:8000 agent-apiAPI 테스트
curl http://localhost:8000/health
curl -X POST http://localhost:8000/ask \
-H "Content-Type: application/json" \
-d '{"question": "What is AI?"}'프로덕션 고려사항
⚠️
보안: 프로덕션에서는 반드시 API 키 인증, Rate Limiting, CORS 설정을 추가하세요
| 항목 | 권장사항 |
|---|---|
| 인증 | API 키 또는 OAuth2 |
| 로깅 | 구조화된 JSON 로그 |
| 모니터링 | Prometheus + Grafana |
| 스케일링 | Kubernetes 또는 Cloud Run |