从零到规模化机器学习:在 Kubernetes 上使用 FastAPI 和 HPA 部署 ONNX 模型

发布: (2025年12月16日 GMT+8 02:42)
2 min read
原文: Dev.to

Source: Dev.to

Cover image for Zero-to-Scale ML: Deploying ONNX Models on Kubernetes with FastAPI and HPA

可扩展的机器学习部署路径需要高性能的 API 与强大的编排。本篇文章将演示如何使用 FastAPI 提供高速接口、使用 Kind 进行 Kubernetes 编排,搭建本地的高可用、自动伸缩推理服务。

Phase 1: The FastAPI Inference Service

我们的 Python 服务负责 ONNX 模型的推理。对 K8s 稳定性至关重要的组件是 /health 接口:

# app.py snippet
# ... model loading logic ...

@app.get("/health")
def health_check():
    # K8s Probes will hit this endpoint frequently
    return {"status": "ok", "model_loaded": True}

# ... /predict endpoint ...

Phase 2: Docker and Kubernetes Deployment

构建镜像(clothing-classifier:latest)并将其加载到 Kind 后,我们定义 Deployment。请注意资源限制和探针的关键配置。

# deployment.yaml (Snippet focusing on probes and resources)
resources:
  requests:
    cpu: "250m"   # For scheduling
    memory: "500Mi"
  limits:
    cpu: "500m"   # To prevent monopolizing the node
    memory: "1Gi"
livenessProbe:
  httpGet: {path: /health, port: 8000}
  initialDelaySeconds: 5
readinessProbe:
  httpGet: {path: /health, port: 8000}
  initialDelaySeconds: 5  # Gives time for the ONNX model to load

Phase 3: Implementing Horizontal Pod Autoscaler (HPA)

可伸缩性由 HPA 负责,而 HPA 需要 Metrics Server 正在运行。

# hpa.yaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: clothing-classifier-hpa
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: clothing-classifier-deployment
  minReplicas: 2
  maxReplicas: 5
  metrics:
  - type: Resource
    resource:
      name: cpu
      target:
        type: Utilization
        averageUtilization: 50  # Scale up if CPU exceeds 50%

Result: 在负载下,HPA 会动态调整副本数量。这正是 弹性、成本效益高的 MLOps 的定义。

阅读完整指南请前往此处

Back to Blog

相关文章

阅读更多 »