Containerization

Containerization is a powerful technique for packaging applications and their dependencies into isolated, portable environments. It’s widely used in AI deployment to ensure consistency, scalability, and ease of management.

This Lesson Will Cover
  • 📦 Containerization fundamentals and benefits
  • 🐳 Docker basics and container creation
  • ☸️ Container orchestration with Kubernetes
  • 🔒 Container security best practices
  • ⚙️ Batch processing with containers

What is Containerization?

A container is a lightweight, standalone package that includes:

  • Code: Your application (e.g., model inference script).
  • Runtime: Libraries, dependencies, and system tools required to run the application.

Benefits of Containers

  • Portability: Containers run the same way across different environments (local, cloud, etc.).
  • Consistency: Eliminate “works on my machine” issues.
  • Efficiency: Containers share the host OS kernel, making them lighter than virtual machines (VMs).

Docker Basics

Docker is the most popular tool for creating and managing containers. Let’s look at how to containerize a model-serving API using Docker.

Dockerfile

A Dockerfile is a script that defines the steps to build a Docker image. Below is an example for a Flask-based API.

Example Dockerfile:

# Base image
FROM python:3.9-slim

# Set working directory
WORKDIR /app

# Copy files into the container
COPY requirements.txt requirements.txt
COPY app.py app.py
COPY model.pkl model.pkl

# Install dependencies
RUN pip install --no-cache-dir -r requirements.txt

# Expose the API port
EXPOSE 5000

# Run the application
CMD ["python", "app.py"]
Building and Running a Dockerfile App
  1. Build the Docker image:
    docker build -t model-api .
    
  2. Run the container:
    docker run -p 5000:5000 model-api
    

This creates a containerized environment for your API, accessible at http://localhost:5000.

Docker Compose

Docker Compose simplifies managing multi-container applications. It uses a YAML file to define services, networks, and volumes.

Example docker-compose.yml:

version: '3'
services:
  model-api:
    build: .
    ports:
      - "5000:5000"
    volumes:
      - ./models:/app/models
    environment:
      - MODEL_PATH=/app/models/model.pkl
Building and Running a Docker Compose App
  1. Start the application:
    docker-compose up
    
  2. Stop the application:
    docker-compose down
    

Container Orchestration with Kubernetes

For larger systems, managing individual containers manually becomes impractical. Kubernetes (K8s) automates the deployment, scaling, and management of containerized applications.

Key Kubernetes Concepts

  • Pod: The smallest deployable unit, which can run one or more containers.
  • Node: A machine (physical or virtual) that runs Pods.
  • Cluster: A collection of nodes managed by Kubernetes.
  • Service: Exposes Pods to the network.

Deploying a Model with Kubernetes

Here’s an example Kubernetes YAML configuration for deploying a model-serving container.

Deployment File (model-deployment.yaml):

This file defines how your application should run and be replicated across the cluster.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: model-api-deployment
spec:
  replicas: 3                    # Creates 3 identical copies of your application
  selector:
    matchLabels:
      app: model-api            # Identifies which pods to manage
  template:
    metadata:
      labels:
        app: model-api          # Label attached to each pod
    spec:
      containers:
      - name: model-api
        image: model-api:latest # Docker image to use
        ports:
        - containerPort: 5000   # Port your application listens on

Service File (model-service.yaml):

This file defines how to access your application from inside or outside the cluster.

apiVersion: v1
kind: Service
metadata:
  name: model-api-service
spec:
  selector:
    app: model-api            # Connects service to pods with this label
  ports:
  - protocol: TCP
    port: 80                 # Port the service listens on
    targetPort: 5000         # Port to forward to (matches containerPort)
  type: LoadBalancer        # Exposes service externally via cloud provider's load balancer

The Deployment manages your application’s lifecycle and scaling, while the Service handles networking and access to your application.

Running on Kubernetes

  1. Apply the configurations:
    kubectl apply -f model-deployment.yaml
    kubectl apply -f model-service.yaml
    
  2. Check the deployment:
    kubectl get pods
    
  3. Access the service:
    • Kubernetes will expose your service via a load balancer or an external IP.

Note: Deploying things with k8s is really hard[1].

End‑to‑End Docker Containerization Workflow
End‑to‑End Docker containerization workflow as described above.

Container Security

Security is a critical consideration for any deployment. Common containerized application vulnerabilities include insecure base images, exposed container ports, running containers as root, unpatched dependencies, and misconfigured access controls.

Best Practices

  • Port Management:
    • Only expose necessary ports and avoid using privileged ports (<1024)
    • Use internal container networks when possible instead of exposing ports
  • Secrets Management:
    • Never hardcode sensitive data in container images
    • Use secure secrets management solutions
  • Run as Non-Root:
    • Avoid running containers as the root user.
  • Use Trusted Base Images:
    • Use official images or scan third-party images for vulnerabilities.
  • Minimize Attack Surface:
    • Use minimal base images like alpine to reduce the number of packages.
  • Image Scanning:
    • Use tools like Docker’s built-in scan or external services (e.g., Snyk).
  • Regular Updates:
    • Keep base images and dependencies updated with security patches
    • Implement automated vulnerability scanning in CI/CD pipeline

Visualizing Containerized Applications

Here is an examples diagram for a containerized ML application with replication that does real-time inference:

Diagram of a containerized ML application with replication for real-time inference
Architecture diagram showing web, mobile, and developer clients routing through an API Gateway to replicated inference containers, which access a shared model registry, config store, and database.

Python Example: Batch Container Execution

Creating containers for ML training and testing ensures reproducible environments across different machines and makes it easier to track and version different experimental configurations.

Here’s an example of running a batch inference job in a Docker container:

Batch job batch_job.py

import pandas as pd
import joblib

# Load model
model = joblib.load("model.pkl")

# Load data
data = pd.read_csv("data.csv")

# Perform batch predictions
data['predictions'] = model.predict(data.drop('label', axis=1))

# Save results
data.to_csv("/app/output/predictions.csv", index=False)

Dockerfile for Batch Job:

FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt requirements.txt
COPY batch_job.py batch_job.py
COPY model.pkl model.pkl
COPY data.csv data.csv
RUN pip install --no-cache-dir -r requirements.txt
CMD ["python", "batch_job.py"]

requirements.txt for app:

numpy==1.24.3
pandas==2.0.3
scikit-learn==1.3.0
joblib==1.3.1
flask==2.3.3
gunicorn==21.2.0
python-dotenv==1.0.0
requests==2.31.0

To run the inference:

  1. Build the container:

    docker build -t batch-inference .
    
  2. Run the container with a volume to persist outputs:

    docker run -v $(pwd)/output:/app/output batch-inference
    

The predictions will be saved to predictions.csv in our mounted output directory.

Conclusion

Containerization is near and dear to my heart (this isn’t the first time I’ve said that about a topic in this course)!

As a tangential aside, there’s a CLI tool I recently found called pipx, which I use to install Python applications in isolated environments, e.g., pipx install llm[2]. It’s like pip, but creates a dedicated virtual environment for each application. This awesome use of containerization keeps my system Python environment clean while making it easy to install and use command-line tools with pip.

Key Takeaways

📦 Containerization provides consistent, portable environments for AI deployments.

🐳 Docker is the primary tool for creating and managing containers.

⚙️ Kubernetes enables automated scaling and management of containerized applications.

🔒 Container security requires careful attention to permissions, ports, and dependencies.

🚀 Containers support both real-time inference APIs and batch processing jobs.

Next: LLM Integration Patterns

That’s the basics of containerization for AI/ML and the end of our first section on AI Deployments.

I loooove developing with Docker. Next, we’ll focus on deployments specifically for LLM applications.

Footnotes


  1. Learn how to actually get your hands dirty with k8s: Deploy an AI Microservice with Kubernetes 40 minute video ↩︎

  2. I’ve got a demo where I install llm with pipx and explain how it works: How to Setup and Run DeepSeek-R1 Locally Using Ollama. ↩︎

Comments (0)

No comments yet.