Published
AI Model Deployment: Docker, Kubernetes and MLOps in Production
Take AI models from notebook to production: Docker images, LLM serving, Kubernetes with GPU scheduling and autoscaling, CI/CD, canary releases and monitoring.
- Written by
- Ali ÖzdurmuşFounder, Veni AI
- Updated
- Reading time
- 6 min read

Deploying an AI model means moving it from a notebook to a production environment where it is reliable, scalable and maintainable. Whether you serve your own fine-tuned model, run an open-weights LLM on company GPUs or wrap a hosted API in your own service, the same engineering basics apply.
Deployment Patterns
1. Batch Inference
Batch data processing, scheduled jobs:
Data Lake → Batch Job → Model Inference → Results Storage2. Real-time Inference
Instant API-based predictions:
Request → API Gateway → Model Server → Response3. Streaming Inference
Continuous data stream processing:
Kafka Stream → Stream Processor → Model → Output Stream4. Edge Deployment
Inference on device:
Mobile/IoT Device → Optimized Model → Local InferenceModel Containerization with Docker
Basic Dockerfile
FROM python:3.11-slim
WORKDIR /app
# System dependencies
RUN apt-get update && apt-get install -y \
libgomp1 \
&& rm -rf /var/lib/apt/lists/*
# Python dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Model and code
COPY model/ ./model/
COPY src/ ./src/
# Port
EXPOSE 8000
# Healthcheck
HEALTHCHECK \
CMD curl -f http://localhost:8000/health || exit 1
# Start command
CMD ["uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "8000"]Multi-stage Build
# Build stage
FROM python:3.11 AS builder
WORKDIR /app
COPY requirements.txt .
RUN pip wheel --no-cache-dir --wheel-dir /wheels -r requirements.txt
# Production stage
FROM python:3.11-slim
WORKDIR /app
COPY /wheels /wheels
RUN pip install --no-cache-dir /wheels/*
COPY . .
CMD ["python", "main.py"]GPU Support
FROM nvidia/cuda:12.1.1-runtime-ubuntu22.04
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
# Python installation
RUN apt-get update && apt-get install -y python3 python3-pip
# PyTorch GPU
RUN pip3 install torch --index-url https://download.pytorch.org/whl/cu121
COPY . /app
WORKDIR /app
CMD ["python3", "inference.py"]Model Serving Frameworks
FastAPI Server
from contextlib import asynccontextmanager
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import torch
model = None
@asynccontextmanager
async def lifespan(app: FastAPI):
global model
model = torch.load("model.pt") # load once at startup
model.eval()
yield
app = FastAPI(lifespan=lifespan)
class PredictionRequest(BaseModel):
text: str
class PredictionResponse(BaseModel):
prediction: str
confidence: float
@app.post("/predict", response_model=PredictionResponse)
async def predict(request: PredictionRequest):
if model is None:
raise HTTPException(500, "Model not loaded")
with torch.no_grad():
output = model(request.text)
return PredictionResponse(
prediction=output["label"],
confidence=output["score"]
)
@app.get("/health")
async def health():
return {"status": "healthy", "model_loaded": model is not None}TorchServe
# Create model archive
torch-model-archiver \
--model-name mymodel \
--version 1.0 \
--model-file model.py \
--serialized-file model.pt \
--handler handler.py
# Start serving
torchserve --start \
--model-store model_store \
--models mymodel=mymodel.marTriton Inference Server
# config.pbtxt
name: "text_classifier"
platform: "pytorch_libtorch"
max_batch_size: 32
input [
{
name: "INPUT__0"
data_type: TYPE_INT64
dims: [ -1 ]
}
]
output [
{
name: "OUTPUT__0"
data_type: TYPE_FP32
dims: [ -1, 2 ]
}
]
instance_group [
{ count: 2, kind: KIND_GPU }
]Serving LLMs
For open-weights language models, use a dedicated inference engine such as vLLM or SGLang instead of a hand-written server. They handle request batching and KV-cache memory, support quantized models and expose OpenAI-compatible endpoints, so applications can switch between a self-hosted and a hosted model by changing a base URL.
Kubernetes Deployment
Basic Deployment
apiVersion: apps/v1
kind: Deployment
metadata:
name: model-server
spec:
replicas: 3
selector:
matchLabels:
app: model-server
template:
metadata:
labels:
app: model-server
spec:
containers:
- name: model-server
image: myregistry/model-server:v1.0
ports:
- containerPort: 8000
resources:
requests:
memory: "2Gi"
cpu: "1"
limits:
memory: "4Gi"
cpu: "2"
livenessProbe:
httpGet:
path: /health
port: 8000
initialDelaySeconds: 30
periodSeconds: 10
readinessProbe:
httpGet:
path: /ready
port: 8000
initialDelaySeconds: 5
periodSeconds: 5GPU Deployment
apiVersion: apps/v1
kind: Deployment
metadata:
name: gpu-model-server
spec:
replicas: 2
template:
spec:
containers:
- name: model
image: myregistry/gpu-model:v1.0
resources:
limits:
nvidia.com/gpu: 1
nodeSelector:
accelerator: nvidia-tesla-t4
tolerations:
- key: "nvidia.com/gpu"
operator: "Exists"
effect: "NoSchedule"Horizontal Pod Autoscaler
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: model-server-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: model-server
minReplicas: 2
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
- type: Pods
pods:
metric:
name: requests_per_second
target:
type: AverageValue
averageValue: 100Service & Ingress
apiVersion: v1
kind: Service
metadata:
name: model-service
spec:
selector:
app: model-server
ports:
- port: 80
targetPort: 8000
type: ClusterIP
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: model-ingress
annotations:
nginx.ingress.kubernetes.io/rate-limit: "100"
spec:
rules:
- host: model.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: model-service
port:
number: 80MLOps Pipeline
CI/CD Pipeline
# .github/workflows/mlops.yml
name: MLOps Pipeline
on:
push:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Run tests
run: pytest tests/
train:
needs: test
runs-on: ubuntu-latest
steps:
- name: Train model
run: python train.py
- name: Evaluate model
run: python evaluate.py
- name: Register model
if: success()
run: python register_model.py
deploy:
needs: train
runs-on: ubuntu-latest
steps:
- name: Build image
run: docker build -t model:${{ github.sha }} .
- name: Push to registry
run: docker push myregistry/model:${{ github.sha }}
- name: Deploy to K8s
run: kubectl set image deployment/model model=myregistry/model:${{ github.sha }}Model Registry
import mlflow
# Registering model
with mlflow.start_run():
mlflow.log_params({"learning_rate": 0.001, "epochs": 10})
mlflow.log_metrics({"accuracy": 0.95, "f1": 0.93})
mlflow.pytorch.log_model(model, "model")
# Loading model
model_uri = "models:/text-classifier/production"
model = mlflow.pytorch.load_model(model_uri)Canary Deployment
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
name: model-service
spec:
hosts:
- model-service
http:
- route:
- destination:
host: model-service-v1
weight: 90
- destination:
host: model-service-v2
weight: 10Monitoring
Prometheus Metrics
from prometheus_client import Counter, Histogram, start_http_server
PREDICTIONS = Counter('predictions_total', 'Total predictions', ['model', 'status'])
LATENCY = Histogram('prediction_latency_seconds', 'Prediction latency')
@LATENCY.time()
def predict(input_data):
result = model(input_data)
PREDICTIONS.labels(model='v1', status='success').inc()
return resultGrafana Dashboard
Key metrics to monitor:
- Request rate (RPS)
- Latency (p50, p95, p99)
- Error rate
- GPU utilization
- Memory usage
- Model drift indicators
Conclusion
Reliable AI in production rests on familiar foundations: reproducible containers, a serving layer that fits the model, Kubernetes for scaling and GPU scheduling, CI/CD with evaluation gates, gradual rollouts and monitoring that includes model-specific signals such as drift.
Veni AI deploys AI applications on cloud, on-premise and Türkiye-hosted infrastructure, and hands over pipelines your team can run. See our services or talk to our engineers.


