Step-by-step guide on deploying ML models to production with expert tips and best practices for a seamless launch.

Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
Dockerfile that installs all dependencies, copies your model and API code into the image, and defines the command to start the application.
// Example Dockerfile
FROM python:3.8-slim // Base image with minimal Python installation
WORKDIR /app // Set working directory in container
COPY requirements.txt . // Copy dependency list
RUN pip install --no-cache-dir -r requirements.txt // Install dependencies
COPY . . // Copy all files in the current directory into the container
EXPOSE 8000 // Expose port where model API runs
CMD ["python", "serve.py"] // Command to start the model serving application
// Example using FastAPI
from fastapi import FastAPI, HTTPException
import uvicorn
import pickle // For loading your pre-trained model
app = FastAPI()
model = pickle.load(open("model.pkl", "rb")) // Load your ML model
@app.post("/predict")
async def predict(data: dict): // Expecting JSON input with required features
try:
input_data = data["features"]
prediction = model.predict([input_data])
return {"prediction": prediction.tolist()}
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))
if name == "main":
uvicorn.run(app, host="0.0.0.0", port=8000) // Run the API server
// Example GitHub Actions workflow snippet (.github/workflows/deploy.yml)
name: Deploy ML Model
on:
push:
branches:
- main
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2 // Check out the repository
- name: Build Docker image
run: docker build -t my-ml-model . // Build image using Dockerfile
deploy:
needs: build
runs-on: ubuntu-latest
steps:
- name: Deploy to production server
run: |
docker login -u ${{ secrets.DOCKER_USERNAME }} -p ${{ secrets.DOCKER_PASSWORD }}
docker push my-ml-model // Push image to container registry
// Additional steps to update production infrastructure could go here
// Example Kubernetes Deployment (deployment.yaml)
apiVersion: apps/v1
kind: Deployment
metadata:
name: ml-model-deployment
spec:
replicas: 3 // Defines number of pod copies for redundancy
selector:
matchLabels:
app: ml-model
template:
metadata:
labels:
app: ml-model
spec:
containers:
- name: ml-model-container
image: my-ml-model:latest // Docker image from your container registry
ports:
- containerPort: 8000 // Port where the API is exposed
apiVersion: v1
kind: Service
metadata:
name: ml-model-service
spec:
type: LoadBalancer // Exposes service externally using a cloud provider's load balancer
ports:
- port: 80
targetPort: 8000 // Maps external port 80 to container port 8000
selector:
app: ml-model
// Example: Simple logging integration in FastAPI
import logging
logging.basicConfig(level=logging.INFO) // Set up basic logging configuration
@app.middleware("http")
async def log_requests(request, call_next):
logging.info(f"Request: {request.method} {request.url}") // Log the incoming request
response = await call_next(request)
logging.info(f"Response status: {response.status_code}") // Log response status
return response
// Example of error handling in FastAPI endpoint
@app.post("/predict")
async def predict(data: dict):
// Validate input and handle potential errors gracefully
try:
input_data = data["features"]
prediction = model.predict([input_data])
return {"prediction": prediction.tolist()}
except KeyError:
// Return a meaningful error message if the required key is missing
raise HTTPException(status_code=400, detail="Missing 'features' key in the input data")
except Exception as e:
// Log the error and return a generic error message
logging.error(f"Error during prediction: {str(e)}")
raise HTTPException(status_code=500, detail="Internal server error")
From startups to enterprises and everything in between, see for yourself our incredible impact.
Need a dedicated strategic tech and growth partner? Discover what RapidDev can do for your business! Book a call with our team to schedule a free, no-obligation consultation. We’ll discuss your project and provide a custom quote at no cost.Â