💡
Hey — It's Sandip Das 👋

Docker provides a consistent, reproducible environment for packaging models and dependencies, eliminating environment-related failures across development and production.

Containerisation enables scalable deployments, CI/CD automation, and seamless collaboration between data science, platform, and operations teams.

⚡ Quick Reference

Keep the momentum going — everything you need on LearnXOps in one place:


📚 Key Learnings

  • The "Works on My Machine" Crisis
  • Four Concepts You Must Know
  • Installing Docker Desktop
  • Dockerfile Deep Dive
  • Containerizing the Iris Project
  • Production-Ready Dockerfile
  • Multi-Container Setup with docker-compose
  • Docker CLI Cheat Sheet

LearnXOps Labs:


🧠 Learn here

The "Works on My Machine" Crisis

ML environments are notoriously fragile. Docker is the industry-standard fix.

You spend three days tuning your Random Forest on the Iris dataset. Accuracy is 96%. You push the code to GitHub, your teammate pulls it, runs python train.py — and immediately gets a ModuleNotFoundError. Sound familiar?

This happens because Python environments are implicit. Your machine has scikit-learn 1.4.2, theirs has 1.2.0. Your CUDA driver is v12, theirs is v11. Your PATH points to a different Conda environment. The code hasn't changed, but the execution context has — and the execution context is everything.

Docker solves this by bundling your code and its entire execution environment into a single portable artifact called an image. Ship the image, not just the code.

Without Docker, different scikit-learn and Python versions make the teammate and CI runs fail; with Docker, one iris-ml:v1.0 image runs identically on the laptop, the teammate machine and CI.
Environment drift (left) vs Docker's portable container (right)
🐋 Docker in production ML
According to the 2024 State of MLOps survey, 78% of ML teams use Docker or container-based packaging as part of their model deployment workflow. It is now the baseline assumption for cloud ML platforms (SageMaker, Vertex AI, Azure ML) — not an advanced topic.

Four Concepts You Must Know

Everything in Docker flows from four primitives. Internalize these and the rest is syntax.

docker build turns a Dockerfile into an image; docker push sends it to a registry; docker run starts containers from it, and a container mounts a volume to persist data.
Docker lifecycle: Dockerfile → build → Image → run → Container

📦 Image
A read-only template that contains the OS, runtime, libraries, and your code. Think of it like a class in OOP — you define it once, instantiate it many times. Stored in a registry (Docker Hub, ECR).

▣ Container
A running instance of an image. Isolated process with its own filesystem, networking, and process space. Like an object instantiated from a class. Ephemeral by default — state doesn't persist unless you use volumes.

📄 Dockerfile
A recipe file with instructions to build an image. Each instruction adds a layer. Starts with FROM (base image), adds files, installs dependencies, sets the default command.

🎼 docker-compose
A YAML tool to orchestrate multiple containers together. Define a training container, an MLflow tracking server, and a PostgreSQL backend — all wired together with a single docker compose up.


Installing Docker Desktop

One-time setup. Docker Desktop bundles the Docker Engine, CLI, and Docker Compose.

01: Download Docker Desktop

Go to https://docs.docker.com/get-started/get-docker/. Choose your OS. On macOS you'll get a .dmg; on Windows an .exe; on Linux follow the package manager instructions. Docker Desktop includes the daemon, CLI, Compose, and a GUI dashboard.

02: Enable WSL 2 backend (Windows only)

Docker on Windows runs Linux containers inside a WSL 2 virtual machine. The installer usually handles this automatically. If prompted, install the WSL 2 Linux kernel update from Microsoft (on current Windows, wsl --update does it). Make WSL 2 the default version: wsl --set-default-version 2.

03: Verify installation

Open a new terminal and confirm everything works:

docker --version
# Docker version 27.0.3, build 7d4bcd8

docker compose version
# Docker Compose version v2.28.1

docker run hello-world
# Unable to find image 'hello-world:latest' locally
# latest: Pulling from library/hello-world
# c1ec31eb5944: Pull complete
# Digest: sha256:d000bc569937abbe195e20322a0d0e...
# Hello from Docker!
# This message shows that your installation appears to be working correctly.
Resource allocation on macOS / Windows
Docker Desktop runs inside a VM. By default it gets 2 CPUs and 2 GB RAM — too little for serious ML. Open Docker Desktop → Settings → Resources and bump it to 4 CPUs and 8 GB RAM (adjust based on your hardware). This matters when running training jobs inside containers.

Dockerfile Deep Dive

A Dockerfile is a series of instructions. Each instruction creates a layer. Understanding layers is key to writing efficient images.

Every Dockerfile starts with a FROM instruction that names the base image. From there you COPY files, RUN commands, set environment variables with ENV, expose ports with EXPOSE, and specify the default startup command with CMD.

dockerfile

# ── Stage 0: choose a base image ──────────────────────────────────
FROM python:3.11-slim

# ── Metadata (optional but good practice) ─────────────────────────
LABEL maintainer="[email protected]"
LABEL version="1.0"
LABEL description="Iris ML training container"

# ── Set working directory inside the container ────────────────────
WORKDIR /app

# ── COPY requirements FIRST (cache optimization — see below) ──────
COPY requirements.txt .

# ── Install dependencies (runs inside the container) ──────────────
RUN pip install --no-cache-dir -r requirements.txt

# ── Copy the rest of the source code ──────────────────────────────
COPY . .

# ── Environment variables ──────────────────────────────────────────
ENV MLFLOW_TRACKING_URI=http://mlflow-server:5000
ENV PYTHONUNBUFFERED=1

# ── Expose a port (informational — doesn't actually publish) ───────
EXPOSE 8080

# ── Default command when container starts ─────────────────────────
CMD ["python", "train.py"]

Each instruction creates an immutable layer. Docker caches layers — if a layer hasn't changed, it reuses the cached version. This is why we copy requirements.txt and install dependencies before copying the source code: changing train.py won't invalidate the dependency install layer.

Six layers from FROM python:3.11-slim at the bottom to ENV and CMD at the top; the first four are cached, COPY . . changes with the code and the layers above it re-run.
Dockerfile layers build bottom-up; Docker caches unchanged layers for fast rebuilds
💡
The golden rule of layer ordering
Put the things that change least often at the top of your Dockerfile. Base image and OS-level packages change rarely, so they always hit the cache. Your training code changes constantly, so it goes last. This turns a 3-minute build into a 10-second rebuild.

Key Dockerfile instructions reference:

InstructionPurposeExampleCache impact
FROMSet base imageFROM python:3.11-slimalways cached
WORKDIRSet working directoryWORKDIR /apprarely changes
COPYCopy files from hostCOPY requirements.txt .invalidated if file changes
ADDLike COPY + auto-extract tarballsADD data.tar.gz /data/prefer COPY unless you need ADD
RUNExecute shell commandRUN pip install -r req.txtinvalidated when prior layers change
ENVSet environment variableENV PYTHONUNBUFFERED=1rarely changes
ARGBuild-time variable (not in image)ARG MODEL_VERSION=v1build-time only
EXPOSEDocument a port (informational)EXPOSE 5000—
VOLUMEDeclare a mount pointVOLUME /mlflow—
CMDDefault run commandCMD ["python","train.py"]always re-evaluated
ENTRYPOINTFixed executable; CMD becomes argsENTRYPOINT ["python"]always re-evaluated

Containerizing the Iris Project

We'll pick up the Iris classifier from earlier days and wrap it in Docker. Here's the target project structure.

iris-mlops/ Project Structure:

iris-mlops/
├── Dockerfile # ← we'll build this
├── docker-compose.yml # ← multi-container setup
├── .dockerignore # ← what NOT to copy
│
├── requirements.txt # pinned dependencies
├── train.py # training script (from Day 8)
├── evaluate.py # optional evaluation helper
│
├── data/
│ └── iris.csv # or we download in train.py
│
├── models/ # ← mounted as Docker volume
│ └── .gitkeep
│
└── mlruns/ # ← MLflow tracking (volume)
└── .gitkeep

First, let's make sure our requirements.txt pins exact versions — this is the contract Docker will enforce:

requirements.txt

# Core ML
scikit-learn==1.4.2
pandas==2.2.2
numpy==1.26.4

# Experiment tracking
mlflow==2.13.2

# Data loading
requests==2.32.3

# Optional: nicer output
tabulate==0.9.0

And the .dockerignore file — equivalent to .gitignore but for the Docker build context. Without this, Docker sends your entire mlruns/, .git/, and virtual environment to the daemon, massively slowing builds.

.dockerignore

# Python
__pycache__/
*.pyc
*.pyo
*.pyd
.Python
*.egg-info/
dist/
build/

# Virtual envs
.venv/
venv/
env/

# ML artifacts (use volumes instead)
mlruns/
models/
*.pkl
*.joblib

# Git
.git/
.gitignore

# IDE
.vscode/
.idea/
*.swp

# OS
.DS_Store
Thumbs.db

The train.py Script

Our training script is Docker-aware: it reads configuration from environment variables, logs to MLflow, and prints evaluation metrics to stdout so docker logs can capture them.

train.py

import os
import json
import logging
import mlflow
import mlflow.sklearn
import pandas as pd
import numpy as np

from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.metrics import (
    accuracy_score, precision_score,
    recall_score, f1_score,
    classification_report
)
from tabulate import tabulate

# ── Logging to stdout (visible via `docker logs <container>`) ────
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s │ %(levelname)-7s │ %(message)s",
    datefmt="%H:%M:%S"
)
log = logging.getLogger("iris-train")

# ── Read config from environment variables ────────────────────────
MLFLOW_URI   = os.getenv("MLFLOW_TRACKING_URI", "file:///app/mlruns")
N_ESTIMATORS = int(os.getenv("N_ESTIMATORS", "100"))
MAX_DEPTH    = os.getenv("MAX_DEPTH", "None")
MAX_DEPTH    = None if MAX_DEPTH == "None" else int(MAX_DEPTH)
RANDOM_SEED  = int(os.getenv("RANDOM_SEED", "42"))
TEST_SIZE    = float(os.getenv("TEST_SIZE", "0.2"))
MODEL_DIR    = os.getenv("MODEL_DIR", "/app/models")

log.info("🐋 Docker Iris Training Container")
log.info("Config: n_estimators=%d  max_depth=%s  seed=%d",
         N_ESTIMATORS, MAX_DEPTH, RANDOM_SEED)

# ── 1. Load data ──────────────────────────────────────────────────
log.info("Loading Iris dataset...")
iris  = load_iris()
X, y  = iris.data, iris.target
df    = pd.DataFrame(X, columns=iris.feature_names)
df["species"] = y
log.info("Dataset: %d samples, %d features, %d classes",
         len(df), len(iris.feature_names), len(iris.target_names))

# ── 2. Split ──────────────────────────────────────────────────────
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=TEST_SIZE, random_state=RANDOM_SEED, stratify=y
)

# ── 3. MLflow tracking ────────────────────────────────────────────
mlflow.set_tracking_uri(MLFLOW_URI)
mlflow.set_experiment("iris-docker-training")

with mlflow.start_run() as run:
    log.info("MLflow run ID: %s", run.info.run_id)

    # Log hyperparams
    mlflow.log_params({
        "n_estimators": N_ESTIMATORS,
        "max_depth":    MAX_DEPTH,
        "test_size":    TEST_SIZE,
        "random_seed":  RANDOM_SEED,
    })

    # ── 4. Train ──────────────────────────────────────────────────
    log.info("Training RandomForestClassifier...")
    model = RandomForestClassifier(
        n_estimators=N_ESTIMATORS,
        max_depth=MAX_DEPTH,
        random_state=RANDOM_SEED,
        n_jobs=-1
    )
    model.fit(X_train, y_train)

    # ── 5. Evaluate ───────────────────────────────────────────────
    y_pred = model.predict(X_test)
    metrics = {
        "accuracy":  round(accuracy_score(y_test, y_pred),  4),
        "precision": round(precision_score(y_test, y_pred, average="macro"), 4),
        "recall":    round(recall_score(y_test, y_pred,    average="macro"), 4),
        "f1":        round(f1_score(y_test, y_pred,        average="macro"), 4),
    }
    cv_scores = cross_val_score(model, X, y, cv=5)
    metrics["cv_mean"] = round(cv_scores.mean(), 4)
    metrics["cv_std"]  = round(cv_scores.std(),  4)

    mlflow.log_metrics(metrics)

    # ── 6. Print evaluation table (visible via docker logs) ───────
    rows = [[k, v] for k, v in metrics.items()]
    print("\n" + "═"*45)
    print("  🎯 IRIS TRAINING RESULTS")
    print("═"*45)
    print(tabulate(rows, headers=["Metric", "Value"], tablefmt="rounded_outline"))
    print("═"*45 + "\n")

    log.info("Classification report:\n%s",
             classification_report(y_test, y_pred, target_names=iris.target_names))

    # ── 7. Log model artifact ─────────────────────────────────────
    mlflow.sklearn.log_model(model, "random_forest_model")

    # ── 8. Save model locally (to mounted volume) ─────────────────
    import joblib, pathlib
    pathlib.Path(MODEL_DIR).mkdir(parents=True, exist_ok=True)
    model_path = f"{MODEL_DIR}/iris_rf_model.pkl"
    joblib.dump(model, model_path)
    log.info("Model saved to %s", model_path)

    # ── 9. Save metrics JSON ──────────────────────────────────────
    metrics_path = f"{MODEL_DIR}/metrics.json"
    with open(metrics_path, "w") as fh:
        json.dump(metrics, fh, indent=2)
    mlflow.log_artifact(metrics_path)
    log.info("Metrics saved to %s", metrics_path)

log.info("✅ Training complete. Run ID: %s", run.info.run_id)
💡
Environment variables as configuration knobs
Reading hyperparameters from os.getenv() means you can run the same container with different settings: docker run -e N_ESTIMATORS=200 -e MAX_DEPTH=10 iris-ml:v1.0. No code changes, no image rebuilds. This is the foundation of reproducible ML pipelines.

Production-Ready Dockerfile

A Dockerfile optimized for ML workloads: fast rebuilds, minimal image size, and security best practices.

dockerfile

# ─────────────────────────────────────────────────────────────────
# Stage 1: Base image
#   python:3.11-slim is ~130 MB vs ~1 GB for python:3.11 (full Debian), uncompressed
#   Use slim unless you need compilers for C extension packages
# ─────────────────────────────────────────────────────────────────
FROM python:3.11-slim

# ─────────────────────────────────────────────────────────────────
# Labels (used by image registries and tooling)
# ─────────────────────────────────────────────────────────────────
LABEL org.opencontainers.image.title="iris-ml-trainer"
LABEL org.opencontainers.image.description="Iris classifier — LearnXOps MLOps Bootcamp Day 11"
LABEL org.opencontainers.image.version="1.0"

# ─────────────────────────────────────────────────────────────────
# System-level dependencies
#   libgomp1: required by sklearn for parallel computation (n_jobs=-1)
#   && rm -rf /var/lib/apt/lists/*  →  clear apt cache to shrink layer
# ─────────────────────────────────────────────────────────────────
RUN apt-get update \
    && apt-get install -y --no-install-recommends \
        libgomp1 \
        curl \
    && rm -rf /var/lib/apt/lists/*

# ─────────────────────────────────────────────────────────────────
# Create non-root user (security best practice)
#   Running as root inside a container is a security risk
# ─────────────────────────────────────────────────────────────────
RUN useradd --create-home --shell /bin/bash mlops

# ─────────────────────────────────────────────────────────────────
# Working directory
# ─────────────────────────────────────────────────────────────────
WORKDIR /app

# ─────────────────────────────────────────────────────────────────
# IMPORTANT: Copy requirements BEFORE source code
#   If only train.py changes, Docker reuses the pip install cache
#   → rebuilds go from ~3 min to ~5 seconds
# ─────────────────────────────────────────────────────────────────
COPY requirements.txt .
RUN pip install --no-cache-dir --upgrade pip \
    && pip install --no-cache-dir -r requirements.txt

# ─────────────────────────────────────────────────────────────────
# Copy application source (after deps — see above)
# ─────────────────────────────────────────────────────────────────
COPY train.py .
COPY data/ ./data/

# ─────────────────────────────────────────────────────────────────
# Create directories for volumes and set ownership
# ─────────────────────────────────────────────────────────────────
RUN mkdir -p /app/models /app/mlruns \
    && chown -R mlops:mlops /app

# ─────────────────────────────────────────────────────────────────
# Switch to non-root user
# ─────────────────────────────────────────────────────────────────
USER mlops

# ─────────────────────────────────────────────────────────────────
# Environment variables (runtime defaults, overrideable via -e)
# ─────────────────────────────────────────────────────────────────
ENV PYTHONUNBUFFERED=1
ENV PYTHONDONTWRITEBYTECODE=1
ENV N_ESTIMATORS=100
ENV MAX_DEPTH=None
ENV RANDOM_SEED=42
ENV TEST_SIZE=0.2
ENV MODEL_DIR=/app/models
ENV MLFLOW_TRACKING_URI=file:///app/mlruns

# ─────────────────────────────────────────────────────────────────
# Declare volume mount points
#   Data written here persists after container exits (if mounted)
# ─────────────────────────────────────────────────────────────────
VOLUME ["/app/models", "/app/mlruns"]

# ─────────────────────────────────────────────────────────────────
# Health check (optional but useful in orchestrated environments)
# ─────────────────────────────────────────────────────────────────
HEALTHCHECK --interval=30s --timeout=10s --retries=3 \
    CMD python -c "import sklearn; print('OK')" || exit 1

# ─────────────────────────────────────────────────────────────────
# Default command
# ─────────────────────────────────────────────────────────────────
CMD ["python", "train.py"]
Layers of the production Dockerfile with approximate sizes: base about 130 MB, apt packages about 5 MB, user under 1 MB, requirements bytes, pip install about 330 MB, source a few KB, CMD 0 B.
What each layer of the production Dockerfile costs (approximate, uncompressed)

Build the Image, Run the Container

Step by step:

Build the image

# Build the image from the current directory (.), tag it iris-ml:v1.0
# -t  = tag (name:version)
# .   = build context (current directory)

docker build -t iris-ml:v1.0 .

# Output (abbreviated):
# [+] Building 182.4s (12/12) FINISHED
# => [1/7] FROM docker.io/library/python:3.11-slim          71.2s
# => [2/7] RUN apt-get update ...                            8.1s
# => [3/7] RUN useradd --create-home ...                     0.3s
# => [4/7] COPY requirements.txt .                           0.1s
# => [5/7] RUN pip install ...                             155.2s  ← fat layer
# => [6/7] COPY train.py .                                   0.1s
# => [7/7] RUN mkdir -p /app/models ...                      0.2s
# => exporting to image                                       1.8s

Run the container (basic)

# Run the container
# --rm   = remove container after it exits (keep it clean)
# -it    = interactive + TTY (see stdout in real time)
# --name = human-readable container name

docker run --rm -it --name iris-trainer iris-ml:v1.0

Run with volumes + environment overrides

# Run with:
# -v  = mount host directories as volumes (persists model + mlruns)
# -e  = override environment variables (hyperparameters)

docker run --rm -it \
  --name iris-trainer \
  -v $(pwd)/models:/app/models \
  -v $(pwd)/mlruns:/app/mlruns \
  -e N_ESTIMATORS=200 \
  -e MAX_DEPTH=10 \
  -e RANDOM_SEED=123 \
  iris-ml:v1.0

# After the run, check host filesystem:
ls ./models/
# iris_rf_model.pkl  metrics.json

Expected container output

09:12:43 │ INFO    │ 🐋 Docker Iris Training Container
09:12:43 │ INFO    │ Config: n_estimators=200 max_depth=10 seed=123
09:12:43 │ INFO    │ Loading Iris dataset...
09:12:43 │ INFO    │ Dataset: 150 samples, 4 features, 3 classes
09:12:44 │ INFO    │ MLflow run ID: a3f8c921d4e044b2...

═════════════════════════════════════════════
 🎯 IRIS TRAINING RESULTS
═════════════════════════════════════════════
╭───────────┬────────╮
│ Metric    │  Value │
├───────────┼────────┤
│ accuracy  │ 0.9667 │
│ precision │ 0.9674 │
│ recall    │ 0.9667 │
│ f1        │ 0.9666 │
│ cv_mean   │ 0.96   │
│ cv_std    │ 0.0249 │
╰───────────┴────────╯
═════════════════════════════════════════════

09:12:45 │ INFO    │ Model saved to /app/models/iris_rf_model.pkl
09:12:45 │ INFO    │ Metrics saved to /app/models/metrics.json
09:12:45 │ INFO    │ ✅ Training complete. Run ID: a3f8c921d4e044b2...

Essential container management commands

# List all images
docker images
# REPOSITORY  TAG    IMAGE ID     CREATED    SIZE
# iris-ml     v1.0   a1b2c3d4e5   2 min ago  462MB

# List running containers
docker ps

# List all containers (including stopped)
docker ps -a

# View container logs
docker logs iris-trainer

# Execute a shell INSIDE a running container (debug)
docker exec -it iris-trainer bash

# Stop a running container
docker stop iris-trainer

# Remove a stopped container
docker rm iris-trainer

# Remove an image
docker rmi iris-ml:v1.0

# Clean up stopped containers, unused networks, unused images and build cache
# (volumes survive unless you add --volumes)
docker system prune -a

Multi-Container Setup with docker-compose

A real MLOps stack needs multiple services: a training job, an MLflow tracking server, and persistent storage. docker-compose wires them together with a single command.

When we run training inside Docker with MLFLOW_TRACKING_URI=file:///app/mlruns, MLflow writes to a local folder. That's fine for solo work. But in a team, you want a shared MLflow tracking server accessible by everyone. docker-compose lets us run both the trainer and the server together:

On iris-net, iris-trainer logs runs to mlflow-server after it is healthy; mlflow-server persists to the mlflow-data volume and publishes port 5000; the trainer writes to ./models.
docker-compose wires the trainer and MLflow tracking server on a shared network

docker-compose.yml

services:

  # ── Service 1: MLflow Tracking Server ─────────────────────────
  mlflow-server:
    image: ghcr.io/mlflow/mlflow:2.13.2
    container_name: iris-mlflow-server
    command: >
      mlflow server
        --backend-store-uri sqlite:////mlflow/mlflow.db
        --artifacts-destination /mlflow/artifacts
        --host 0.0.0.0
        --port 5000
    ports:
      - "5000:5000"            # expose to host (localhost:5000)
    volumes:
      - mlflow-data:/mlflow   # named volume for persistence
    networks:
      - iris-net
    healthcheck:
      test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:5000/health')"]  # no curl in this image
      interval: 10s
      timeout: 5s
      retries: 5
      start_period: 15s

  # ── Service 2: Iris Trainer ────────────────────────────────────
  iris-trainer:
    build:
      context: .            # build from Dockerfile in current dir
      dockerfile: Dockerfile
    image: iris-ml:v1.0    # tag the built image
    container_name: iris-trainer
    depends_on:
      mlflow-server:
        condition: service_healthy   # wait for MLflow to be ready
    environment:
      MLFLOW_TRACKING_URI: http://mlflow-server:5000
      N_ESTIMATORS: 150
      MAX_DEPTH: "None"
      RANDOM_SEED: 42
      TEST_SIZE: "0.2"
    volumes:
      - ./models:/app/models   # mount local ./models into container
    networks:
      - iris-net
    restart: "no"             # training runs once; don't auto-restart

# ── Shared named volume ────────────────────────────────────────
volumes:
  mlflow-data:
    driver: local

# ── Shared network ─────────────────────────────────────────────
networks:
  iris-net:
    driver: bridge

docker compose commands

# Build images + start all services
docker compose up --build

# Start in background (detached mode)
docker compose up -d --build

# Run only the trainer (MLflow server already running)
docker compose run --rm iris-trainer

# View logs from all services
docker compose logs -f

# View logs from one service
docker compose logs -f iris-trainer

# Stop all services
docker compose down

# Stop and remove volumes (CAREFUL: deletes mlruns data)
docker compose down -v

# Check running services
docker compose ps

e.g. docker compose up --build

[+] Building 8.2s (12/12) FINISHED              ← fast: deps layer cached
[+] Running 4/4
 ✔ Network iris-mlops_iris-net       Created
 ✔ Volume "iris-mlops_mlflow-data"   Created
 ✔ Container iris-mlflow-server      Healthy
 ✔ Container iris-trainer            Started
iris-mlflow-server  | [INFO] Listening at: http://0.0.0.0:5000
iris-trainer        | 09:12:45 │ INFO    │ 🐋 Docker Iris Training Container
iris-trainer        | 09:12:45 │ INFO    │ Loading Iris dataset...
iris-trainer        | ...
iris-trainer        | 09:12:47 │ INFO    │ ✅ Training complete. Run ID: ...
iris-trainer exited with code 0

# MLflow UI: http://localhost:5000

Containers vs VMs — What's the Difference?

A common interview question. Understanding this helps you explain Docker's performance characteristics.

Virtual machines each carry a guest OS on a hypervisor; containers carry only libraries and app code and share the host kernel through the Docker Engine.
VMs virtualize the full hardware stack; containers share the host OS kernel
DimensionVirtual MachineDocker Container
Isolation levelFull OS — hypervisor levelProcess level — namespace + cgroup
Startup time30 seconds to minutes<1 second
Image size1–20 GB (full OS)50–500 MB (app + libs only)
Performance overhead~2–10% (virtualized hardware)~1–2% (native kernel)
OS per instanceEach VM has its own full OSShare host OS kernel
Security boundaryStronger (hardware-level)Weaker (kernel sharing)
Best forOS-level isolation, mixed OSMicroservices, ML pipelines, CI/CD
ML trainingoverkill for most use casesideal — fast, reproducible, portable

Shrinking Your ML Image

A full scikit-learn + MLflow image can balloon to 1.5 GB. These techniques bring it down to under 500 MB without sacrificing functionality.

  • Use -slim or -alpine base images. python:3.11-slim is ~130 MB vs ~1 GB for python:3.11. Note: alpine uses musl libc which can break some Python C extensions (numpy, scipy). Use slim for ML.
  • Combine RUN commands. Each RUN is a layer. Chain apt commands with && and clean up in the same layer: apt-get install ... && rm -rf /var/lib/apt/lists/*
  • Use --no-cache-dir for pip. Pip's local cache is wasted space inside Docker. Always: pip install --no-cache-dir -r requirements.txt
  • Multi-stage builds for GPU. Stage 1: install CUDA + build tools. Stage 2: COPY --from=builder only the compiled artifacts. Your final image is clean.
  • Pin exact versions in requirements.txt. scikit-learn==1.4.2 not scikit-learn>=1.4. Pinning ensures the image builds identically six months from now.
  • Never install dev tools in production images. jupyter, matplotlib, pytest — great for development, wasteful in a training container. Use build-time ARGs or separate Dockerfiles.

Multi-stage build (advanced)

# ── Stage 1: Build environment (includes compilers/dev tools) ────
FROM python:3.11-slim AS builder

RUN apt-get update \
    && apt-get install -y --no-install-recommends \
        gcc g++ libgomp1 \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /build
COPY requirements.txt .
RUN pip install --no-cache-dir --target /build/packages -r requirements.txt


# ── Stage 2: Runtime image (no compilers, no dev tools) ──────────
FROM python:3.11-slim AS runtime

RUN apt-get update \
    && apt-get install -y --no-install-recommends libgomp1 \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /app

# Copy only the installed packages from builder stage
COPY --from=builder /build/packages /usr/local/lib/python3.11/site-packages

COPY train.py .
RUN useradd --create-home mlops && chown -R mlops:mlops /app
USER mlops

ENV PYTHONUNBUFFERED=1
CMD ["python", "train.py"]

# Result: ~462 MB vs ~480 MB  (gcc/g++ compilers not in final image)
Bar chart: python:3.11 full base about 1 GB, final iris-ml image about 462 MB, pip dependencies about 330 MB, python:3.11-slim base about 130 MB.
Approximate uncompressed sizes: the pip layer dominates, the slim base keeps the rest small

Docker + MLflow + DVC — Complete Picture

Docker isn't standalone. It's the packaging layer in your full MLOps stack. Here's how everything from the first 11 days fits together.

Git and DVC, train.py with MLflow and the Dockerfile build the iris-ml image; its container logs to MLflow and saves the model; the same image ships to SageMaker, Kubernetes or ECS.
Docker (Day 11) is the packaging layer connecting your code to cloud deployment

Docker CLI Cheat Sheet

The commands you'll use every day!

# ── IMAGES ──────────────────────────────────────────────────────
docker build -t name:tag .             # build image from current dir
docker build -t name:tag -f alt.Dockerfile .  # specify Dockerfile
docker images                          # list all images
docker rmi name:tag                    # delete image
docker pull python:3.11-slim           # download image from registry
docker push name:tag                   # upload to registry
docker history name:tag                # show layers and sizes
docker inspect name:tag                # full image metadata JSON

# ── CONTAINERS ──────────────────────────────────────────────────
docker run --rm -it name:tag           # run (remove after exit)
docker run -d --name myc name:tag      # run in background
docker run -e VAR=val name:tag         # set env var
docker run -v /host:/container name:t  # mount volume
docker run -p 8080:80 name:tag         # map port host:container
docker ps                              # list running containers
docker ps -a                           # list all containers
docker logs -f container_id            # stream container logs
docker exec -it container_id bash      # shell into running container
docker stop container_id               # graceful stop
docker kill container_id               # force stop
docker rm container_id                 # delete stopped container

# ── VOLUMES ─────────────────────────────────────────────────────
docker volume create my-data           # create named volume
docker volume ls                       # list volumes
docker volume inspect my-data          # volume details
docker volume rm my-data               # delete volume

# ── DOCKER COMPOSE ──────────────────────────────────────────────
docker compose up                      # start all services
docker compose up --build              # rebuild images then start
docker compose up -d                   # detached (background)
docker compose down                    # stop and remove containers
docker compose down -v                 # also remove volumes
docker compose ps                      # service status
docker compose logs -f service_name    # stream service logs
docker compose run --rm service cmd    # run one-off command
docker compose exec service bash       # shell into running service

# ── CLEANUP ─────────────────────────────────────────────────────
docker system prune                    # stopped containers, unused networks, dangling images
docker system prune -a                 # also remove unused images
docker system df                       # disk usage breakdown

Docker is a foundational skill for modern MLOps, turning ML applications into portable and reproducible artifacts. It bridges the gap between development and production, ensuring consistency across environments.

Furthermore, Docker simplifies deployment, scaling, and automation workflows.

Mastering containerization is a key step toward building reliable and production-ready ML systems.


⚡ Quick Reference

Keep the momentum going — everything you need on LearnXOps in one place:

Share this post