AI Model Deployment with Kubernetes and Docker: Production Guide
Learn how to deploy AI models to production using Kubernetes and Docker. Complete guide covering containerization, orchestration, scaling, and monitoring.
AI Model Deployment with Kubernetes and Docker: Production Guide ๐
TL;DR โ This comprehensive guide teaches you how to deploy AI models to production using Kubernetes and Docker. We'll cover containerization, orchestration, auto-scaling, monitoring, and best practices for running AI workloads at scale.
Table of Contents
- Why Kubernetes for AI Deployment
- Prerequisites and Setup
- Containerizing Your AI Model
- Creating Kubernetes Manifests
- Setting Up Model Serving
- Implementing Auto-scaling
- Monitoring and Logging
- CI/CD Pipeline Integration
- Security Best Practices
- Troubleshooting Common Issues
Why Kubernetes for AI Deployment
Kubernetes has become the de facto standard for deploying AI models in production environments. Here's why:
Key Benefits
- Scalability: Automatically scale based on demand
- Resource Management: Efficient GPU and CPU allocation
- High Availability: Built-in fault tolerance and recovery
- Version Management: Easy model updates and rollbacks
- Multi-tenancy: Run multiple models on shared infrastructure
Real-World Use Cases
- Netflix: Serves millions of ML predictions daily
- Uber: Powers real-time pricing and routing
- Spotify: Delivers personalized recommendations
- Airbnb: Dynamic pricing and fraud detection
Prerequisites and Setup
Required Tools
1# Install Docker2curl -fsSL https://get.docker.com -o get-docker.sh3sh get-docker.sh45# Install kubectl6curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"7chmod +x kubectl8sudo mv kubectl /usr/local/bin/910# Install Helm11curl https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3 | bash1213# Install kind (for local testing)14go install sigs.k8s.io/kind@v0.20.0
Local Kubernetes Cluster
1# Create local cluster with GPU support2cat <<EOF > kind-config.yaml3kind: Cluster4apiVersion: kind.x-k8s.io/v1alpha45nodes:6- role: control-plane7 extraMounts:8 - hostPath: /dev/nvidia09 containerPath: /dev/nvidia010 - hostPath: /dev/nvidiactl11 containerPath: /dev/nvidiactl12 - hostPath: /dev/nvidia-uvm13 containerPath: /dev/nvidia-uvm14EOF1516kind create cluster --config kind-config.yaml --name ai-cluster
Containerizing Your AI Model
Step 1: Create Model Server
1# app.py - FastAPI model server2from fastapi import FastAPI, HTTPException3from pydantic import BaseModel4import torch5import numpy as np6import logging7from typing import List, Dict, Any8import uvicorn9import os1011# Configure logging12logging.basicConfig(level=logging.INFO)13logger = logging.getLogger(__name__)1415app = FastAPI(title="AI Model API", version="1.0.0")1617class PredictionRequest(BaseModel):18 data: List[List[float]]1920class PredictionResponse(BaseModel):21 predictions: List[float]22 model_version: str23 processing_time: float2425class ModelServer:26 def __init__(self):27 self.model = None28 self.model_version = os.getenv("MODEL_VERSION", "1.0.0")29 self.load_model()3031 def load_model(self):32 """Load the trained model"""33 try:34 model_path = os.getenv("MODEL_PATH", "/app/models/model.pt")35 self.model = torch.load(model_path, map_location="cpu")36 self.model.eval()37 logger.info(f"Model loaded successfully from {model_path}")38 except Exception as e:39 logger.error(f"Failed to load model: {e}")40 raise4142 def predict(self, data: np.ndarray) -> np.ndarray:43 """Make predictions"""44 with torch.no_grad():45 tensor_data = torch.FloatTensor(data)46 predictions = self.model(tensor_data)47 return predictions.numpy()4849# Global model instance50model_server = ModelServer()5152@app.get("/health")53async def health_check():54 """Health check endpoint"""55 return {"status": "healthy", "model_version": model_server.model_version}5657@app.get("/ready")58async def readiness_check():59 """Readiness check endpoint"""60 if model_server.model is None:61 raise HTTPException(status_code=503, detail="Model not loaded")62 return {"status": "ready", "model_version": model_server.model_version}6364@app.post("/predict", response_model=PredictionResponse)65async def predict(request: PredictionRequest):66 """Make predictions"""67 import time68 start_time = time.time()6970 try:71 data = np.array(request.data)72 predictions = model_server.predict(data)73 processing_time = time.time() - start_time7475 return PredictionResponse(76 predictions=predictions.tolist(),77 model_version=model_server.model_version,78 processing_time=processing_time79 )80 except Exception as e:81 logger.error(f"Prediction error: {e}")82 raise HTTPException(status_code=500, detail=str(e))8384if __name__ == "__main__":85 uvicorn.run(app, host="0.0.0.0", port=8000)
Step 2: Create Dockerfile
1# Dockerfile2FROM python:3.10-slim34# Install system dependencies5RUN apt-get update && apt-get install -y \\6 gcc \\7 g++ \\8 && rm -rf /var/lib/apt/lists/*910# Set working directory11WORKDIR /app1213# Copy requirements14COPY requirements.txt .1516# Install Python dependencies17RUN pip install --no-cache-dir -r requirements.txt1819# Copy application code20COPY app.py .21COPY models/ ./models/2223# Create non-root user24RUN useradd -m -u 1000 appuser && chown -R appuser:appuser /app25USER appuser2627# Expose port28EXPOSE 80002930# Health check31HEALTHCHECK --interval=30s --timeout=30s --start-period=5s --retries=3 \\32 CMD curl -f http://localhost:8000/health || exit 13334# Run application35CMD ["python", "app.py"]
Step 3: Requirements File
1# requirements.txt2fastapi==0.104.13uvicorn[standard]==0.24.04torch==2.1.05numpy==1.24.36pydantic==2.4.27python-multipart==0.0.6
Step 4: Build and Test
1# Build Docker image2docker build -t ai-model:v1.0.0 .34# Test locally5docker run -p 8000:8000 ai-model:v1.0.067# Test endpoints8curl http://localhost:8000/health9curl -X POST http://localhost:8000/predict \\10 -H "Content-Type: application/json" \\11 -d '{"data": [[1.0, 2.0, 3.0]]}'
Creating Kubernetes Manifests
Step 1: Deployment Configuration
1# deployment.yaml2apiVersion: apps/v13kind: Deployment4metadata:5 name: ai-model-deployment6 labels:7 app: ai-model8 version: v1.0.09spec:10 replicas: 311 selector:12 matchLabels:13 app: ai-model14 template:15 metadata:16 labels:17 app: ai-model18 version: v1.0.019 spec:20 containers:21 - name: ai-model22 image: ai-model:v1.0.023 ports:24 - containerPort: 800025 env:26 - name: MODEL_VERSION27 value: "1.0.0"28 - name: MODEL_PATH29 value: "/app/models/model.pt"30 resources:31 requests:32 memory: "512Mi"33 cpu: "250m"34 limits:35 memory: "2Gi"36 cpu: "1000m"37 livenessProbe:38 httpGet:39 path: /health40 port: 800041 initialDelaySeconds: 3042 periodSeconds: 1043 readinessProbe:44 httpGet:45 path: /ready46 port: 800047 initialDelaySeconds: 548 periodSeconds: 549 volumeMounts:50 - name: model-storage51 mountPath: /app/models52 volumes:53 - name: model-storage54 persistentVolumeClaim:55 claimName: model-pvc56---57apiVersion: v158kind: PersistentVolumeClaim59metadata:60 name: model-pvc61spec:62 accessModes:63 - ReadOnlyMany64 resources:65 requests:66 storage: 10Gi
Step 2: Service Configuration
1# service.yaml2apiVersion: v13kind: Service4metadata:5 name: ai-model-service6 labels:7 app: ai-model8spec:9 selector:10 app: ai-model11 ports:12 - port: 8013 targetPort: 800014 protocol: TCP15 type: ClusterIP16---17apiVersion: networking.k8s.io/v118kind: Ingress19metadata:20 name: ai-model-ingress21 annotations:22 nginx.ingress.kubernetes.io/rewrite-target: /23 nginx.ingress.kubernetes.io/ssl-redirect: "true"24spec:25 tls:26 - hosts:27 - ai-model.example.com28 secretName: ai-model-tls29 rules:30 - host: ai-model.example.com31 http:32 paths:33 - path: /34 pathType: Prefix35 backend:36 service:37 name: ai-model-service38 port:39 number: 80
Setting Up Model Serving
Step 1: Deploy to Kubernetes
1# Apply configurations2kubectl apply -f deployment.yaml3kubectl apply -f service.yaml45# Check deployment status6kubectl get deployments7kubectl get pods8kubectl get services910# View logs11kubectl logs -l app=ai-model -f
Step 2: Configure Load Balancing
1# hpa.yaml - Horizontal Pod Autoscaler2apiVersion: autoscaling/v23kind: HorizontalPodAutoscaler4metadata:5 name: ai-model-hpa6spec:7 scaleTargetRef:8 apiVersion: apps/v19 kind: Deployment10 name: ai-model-deployment11 minReplicas: 212 maxReplicas: 1013 metrics:14 - type: Resource15 resource:16 name: cpu17 target:18 type: Utilization19 averageUtilization: 7020 - type: Resource21 resource:22 name: memory23 target:24 type: Utilization25 averageUtilization: 80
Step 3: GPU Support (Optional)
1# gpu-deployment.yaml2apiVersion: apps/v13kind: Deployment4metadata:5 name: ai-model-gpu-deployment6spec:7 replicas: 18 selector:9 matchLabels:10 app: ai-model-gpu11 template:12 metadata:13 labels:14 app: ai-model-gpu15 spec:16 containers:17 - name: ai-model18 image: ai-model:v1.0.0-gpu19 resources:20 limits:21 nvidia.com/gpu: 122 requests:23 nvidia.com/gpu: 124 env:25 - name: CUDA_VISIBLE_DEVICES26 value: "0"27 nodeSelector:28 accelerator: nvidia-tesla-k80
Implementing Auto-scaling
Step 1: Metrics Server Setup
1# Install metrics server2kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml34# Verify installation5kubectl get deployment metrics-server -n kube-system
Step 2: Custom Metrics (Prometheus)
1# prometheus-config.yaml2apiVersion: v13kind: ConfigMap4metadata:5 name: prometheus-config6data:7 prometheus.yml: |8 global:9 scrape_interval: 15s10 scrape_configs:11 - job_name: 'ai-model'12 static_configs:13 - targets: ['ai-model-service:80']14 metrics_path: /metrics15 scrape_interval: 5s
Step 3: Custom HPA with Prometheus
1# custom-hpa.yaml2apiVersion: autoscaling/v23kind: HorizontalPodAutoscaler4metadata:5 name: ai-model-custom-hpa6spec:7 scaleTargetRef:8 apiVersion: apps/v19 kind: Deployment10 name: ai-model-deployment11 minReplicas: 212 maxReplicas: 2013 metrics:14 - type: Pods15 pods:16 metric:17 name: requests_per_second18 target:19 type: AverageValue20 averageValue: "100"21 behavior:22 scaleUp:23 stabilizationWindowSeconds: 6024 policies:25 - type: Percent26 value: 10027 periodSeconds: 1528 scaleDown:29 stabilizationWindowSeconds: 30030 policies:31 - type: Percent32 value: 1033 periodSeconds: 60
Monitoring and Logging
Step 1: Prometheus and Grafana
1# Install Prometheus Operator2helm repo add prometheus-community https://prometheus-community.github.io/helm-charts3helm repo update45helm install prometheus prometheus-community/kube-prometheus-stack \\6 --namespace monitoring \\7 --create-namespace \\8 --set grafana.adminPassword=admin123
Step 2: Custom Metrics in Application
1# metrics.py2from prometheus_client import Counter, Histogram, Gauge, generate_latest3import time45# Define metrics6REQUEST_COUNT = Counter('ai_model_requests_total', 'Total requests', ['method', 'endpoint'])7REQUEST_LATENCY = Histogram('ai_model_request_duration_seconds', 'Request latency')8MODEL_PREDICTIONS = Counter('ai_model_predictions_total', 'Total predictions made')9ACTIVE_CONNECTIONS = Gauge('ai_model_active_connections', 'Active connections')1011# Middleware for FastAPI12@app.middleware("http")13async def add_prometheus_middleware(request, call_next):14 start_time = time.time()1516 # Increment request counter17 REQUEST_COUNT.labels(method=request.method, endpoint=request.url.path).inc()1819 # Process request20 response = await call_next(request)2122 # Record latency23 REQUEST_LATENCY.observe(time.time() - start_time)2425 return response2627@app.get("/metrics")28async def metrics():29 """Prometheus metrics endpoint"""30 return Response(generate_latest(), media_type="text/plain")
Step 3: Grafana Dashboard
1{2 "dashboard": {3 "title": "AI Model Monitoring",4 "panels": [5 {6 "title": "Request Rate",7 "type": "graph",8 "targets": [9 {10 "expr": "rate(ai_model_requests_total[5m])",11 "legendFormat": "{{method}} {{endpoint}}"12 }13 ]14 },15 {16 "title": "Response Time",17 "type": "graph",18 "targets": [19 {20 "expr": "histogram_quantile(0.95, ai_model_request_duration_seconds_bucket)",21 "legendFormat": "95th percentile"22 }23 ]24 },25 {26 "title": "Pod Count",27 "type": "stat",28 "targets": [29 {30 "expr": "kube_deployment_status_replicas{deployment=\"ai-model-deployment\"}",31 "legendFormat": "Replicas"32 }33 ]34 }35 ]36 }37}
CI/CD Pipeline Integration
Step 1: GitHub Actions Workflow
1# .github/workflows/deploy.yml2name: Deploy AI Model34on:5 push:6 branches: [main]7 pull_request:8 branches: [main]910env:11 REGISTRY: ghcr.io12 IMAGE_NAME: ${{ github.repository }}/ai-model1314jobs:15 test:16 runs-on: ubuntu-latest17 steps:18 - uses: actions/checkout@v41920 - name: Set up Python21 uses: actions/setup-python@v422 with:23 python-version: '3.10'2425 - name: Install dependencies26 run: |27 pip install -r requirements.txt28 pip install pytest2930 - name: Run tests31 run: pytest tests/3233 build:34 needs: test35 runs-on: ubuntu-latest36 permissions:37 contents: read38 packages: write3940 steps:41 - uses: actions/checkout@v44243 - name: Log in to Container Registry44 uses: docker/login-action@v345 with:46 registry: ${{ env.REGISTRY }}47 username: ${{ github.actor }}48 password: ${{ secrets.GITHUB_TOKEN }}4950 - name: Extract metadata51 id: meta52 uses: docker/metadata-action@v553 with:54 images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}55 tags: |56 type=ref,event=branch57 type=ref,event=pr58 type=sha5960 - name: Build and push Docker image61 uses: docker/build-push-action@v562 with:63 context: .64 push: true65 tags: ${{ steps.meta.outputs.tags }}66 labels: ${{ steps.meta.outputs.labels }}6768 deploy:69 needs: build70 runs-on: ubuntu-latest71 if: github.ref == 'refs/heads/main'7273 steps:74 - uses: actions/checkout@v47576 - name: Configure kubectl77 run: |78 echo "${{ secrets.KUBE_CONFIG }}" | base64 -d > kubeconfig79 export KUBECONFIG=kubeconfig8081 - name: Deploy to Kubernetes82 run: |83 export KUBECONFIG=kubeconfig84 sed -i "s|ai-model:v1.0.0|${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.sha }}|g" deployment.yaml85 kubectl apply -f deployment.yaml86 kubectl apply -f service.yaml87 kubectl rollout status deployment/ai-model-deployment
Step 2: ArgoCD GitOps (Alternative)
1# argocd-application.yaml2apiVersion: argoproj.io/v1alpha13kind: Application4metadata:5 name: ai-model6 namespace: argocd7spec:8 project: default9 source:10 repoURL: https://github.com/your-org/ai-model-k8s11 targetRevision: HEAD12 path: manifests13 destination:14 server: https://kubernetes.default.svc15 namespace: ai-models16 syncPolicy:17 automated:18 prune: true19 selfHeal: true20 syncOptions:21 - CreateNamespace=true
Security Best Practices
Step 1: Network Policies
1# network-policy.yaml2apiVersion: networking.k8s.io/v13kind: NetworkPolicy4metadata:5 name: ai-model-network-policy6spec:7 podSelector:8 matchLabels:9 app: ai-model10 policyTypes:11 - Ingress12 - Egress13 ingress:14 - from:15 - namespaceSelector:16 matchLabels:17 name: ingress-nginx18 ports:19 - protocol: TCP20 port: 800021 egress:22 - to: []23 ports:24 - protocol: TCP25 port: 443 # HTTPS26 - protocol: TCP27 port: 53 # DNS28 - protocol: UDP29 port: 53 # DNS
Step 2: Pod Security Standards
1# pod-security-policy.yaml2apiVersion: v13kind: Pod4metadata:5 name: ai-model-pod6spec:7 securityContext:8 runAsNonRoot: true9 runAsUser: 100010 fsGroup: 100011 seccompProfile:12 type: RuntimeDefault13 containers:14 - name: ai-model15 image: ai-model:v1.0.016 securityContext:17 allowPrivilegeEscalation: false18 readOnlyRootFilesystem: true19 capabilities:20 drop:21 - ALL22 volumeMounts:23 - name: tmp24 mountPath: /tmp25 - name: var-tmp26 mountPath: /var/tmp27 volumes:28 - name: tmp29 emptyDir: {}30 - name: var-tmp31 emptyDir: {}
Step 3: Secrets Management
1# secret.yaml2apiVersion: v13kind: Secret4metadata:5 name: ai-model-secrets6type: Opaque7data:8 api-key: <base64-encoded-api-key>9 db-password: <base64-encoded-password>10---11apiVersion: apps/v112kind: Deployment13metadata:14 name: ai-model-deployment15spec:16 template:17 spec:18 containers:19 - name: ai-model20 env:21 - name: API_KEY22 valueFrom:23 secretKeyRef:24 name: ai-model-secrets25 key: api-key
Troubleshooting Common Issues
Issue 1: Pod Startup Failures
1# Debug pod issues2kubectl describe pod <pod-name>3kubectl logs <pod-name> --previous45# Common solutions6# 1. Check resource limits7kubectl top pods8kubectl describe nodes910# 2. Verify image availability11docker pull ai-model:v1.0.01213# 3. Check secrets and configmaps14kubectl get secrets15kubectl describe secret ai-model-secrets
Issue 2: Service Discovery Problems
1# Test service connectivity2kubectl run debug --image=busybox -it --rm -- sh3nslookup ai-model-service4wget -qO- http://ai-model-service/health56# Check endpoints7kubectl get endpoints ai-model-service8kubectl describe service ai-model-service
Issue 3: Performance Issues
1# Monitor resource usage2kubectl top pods3kubectl top nodes45# Check HPA status6kubectl get hpa7kubectl describe hpa ai-model-hpa89# Analyze metrics10kubectl port-forward svc/prometheus-server 9090:8011# Visit http://localhost:9090
Issue 4: GPU Not Available
1# Check GPU nodes2kubectl get nodes -l accelerator=nvidia-tesla-k8034# Verify GPU plugin5kubectl get daemonset nvidia-device-plugin-daemonset -n kube-system67# Check pod GPU allocation8kubectl describe pod <gpu-pod-name>
Conclusion
Deploying AI models with Kubernetes and Docker provides a robust, scalable foundation for production AI systems. Key takeaways:
Best Practices Summary
- Containerize properly with health checks and security
- Use resource limits to prevent resource starvation
- Implement monitoring from day one
- Automate deployments with CI/CD pipelines
- Plan for scaling with HPA and cluster autoscaling
- Secure by default with network policies and RBAC
Next Steps
- Implement A/B testing for model versions
- Add distributed tracing with Jaeger
- Explore service mesh with Istio
- Implement chaos engineering practices
- Consider multi-cluster deployments
Resources
Ready to deploy your AI models at scale? Start with a simple deployment and gradually add complexity as your needs grow. Remember: production readiness is a journey, not a destination! ๐
Related Posts
Deploying AI Applications: Production Best Practices and Scaling
Learn production deployment strategies for AI applications including containerization, monitoring, scaling, and maintaining AI systems in enterprise environments.
AI Automation with Python: Complete Practical Guide
Master AI automation with Python. Build intelligent workflows, automate data processing, and create smart systems that work 24/7.
AI Automation Workflows: From Concept to Production
Master the art of building production-ready AI automation workflows. Learn design patterns, error handling, monitoring, and scaling strategies for enterprise AI systems.