πŸ’‘
Hey β€” It's Sandip Das πŸ‘‹

Docker Compose enables us to orchestrate complete multi-service ML environments,such as MLflow, training pipelines, databases, and APIs with a single command, ensuring reproducible, production-like development.

Mastering it simplifies local testing, accelerates collaboration, and eliminates environment inconsistencies before deployment to Kubernetes or the cloud.

⚑ Quick Reference

Keep the momentum going β€” everything you need on LearnXOps in one place:


πŸ“š Key Learnings

  • Why Docker Compose for ML?
  • Architecture: What We're Building
  • Docker Compose Core Concepts
  • Project File Structure
  • The .env File
  • Writing the docker-compose.yml
  • The Training Script
  • Service Startup Lifecycle
  • Running the Stack
  • Troubleshooting Common Issues
  • Key Concepts Quick Reference

🧠 Learn here

Why Docker Compose for ML?

A real ML system is never a single process. Even locally, you need a tracking server, a database (or file store), and your training code β€” all running and talking to each other at the same time.

πŸ”₯ The Old Way (Pain)

Open Tab 1: start MLflow. Open Tab 2: export env vars. Open Tab 3: run training. Lose a terminal. Everything breaks. Repeat every time you restart your laptop.

βœ… The Compose Way

One docker compose up command. Every service starts in the right order, shares a private network, mounts the right volumes, and tears down cleanly with one Ctrl+C.

πŸ“¦ Reproducibility
Your entire local ML platform is described in a single docker-compose.yml file. Commit it to Git. Any teammate clones the repo and runs the exact same environment.

πŸ“Œ Docker Compose v2 vs v1
Modern Docker Desktop ships with Docker Compose v2, integrated as a Docker CLI plugin. The command is docker compose (no hyphen). The old standalone binary was docker-compose (hyphen). This article uses v2 syntax throughout. Run docker compose version to verify.


Architecture: What We're Building

Two containers on a shared private network. The training container knows the MLflow server only by its service name β€” Docker's internal DNS handles the rest.

On the ml_network bridge, the trainer sends HTTP to http://mlflow:5000 after mlflow is healthy; mlflow stores data in the mlflow_data and mlflow_artifacts named volumes and publishes port 5000 to the browser.
Two-service Compose stack. The trainer reaches MLflow via DNS name "mlflow" on port 5000. Your browser hits localhost:5000.

The key insight in the diagram above: the trainer container never needs the host IP or a hardcoded container IP. Docker Compose creates an internal DNS where the service name mlflow resolves automatically. Set MLFLOW_TRACKING_URI=http://mlflow:5000 and you're done.


Docker Compose Core Concepts

Before writing YAML, understand the four primitives. Everything in a Compose file maps to one of these.

docker-compose.yml with name iris_mlops and top-level services (mlflow, trainer), networks (ml_network) and volumes (mlflow_data, mlflow_artifacts); no version key; ${VAR} interpolation from .env.
Top-level structure of a docker-compose.yml file

πŸ”§ services
Each service becomes one running container. You define its image (or build context), environment, ports, volumes, and startup dependencies.

🌐 networks
An isolated virtual LAN. Services on the same network find each other by service name. By default Compose creates one bridge network for your entire project.

πŸ“¦ volumes
Named Docker-managed storage that persists between docker compose up/down cycles. Use these for MLflow experiment data and artifact stores.

βš™οΈ configs / secrets
Inject configuration files or sensitive data into containers without baking them into images. Essential for production; useful even locally.

⏳ depends_on
Declare startup ordering and wait for healthchecks. Your trainer will wait for MLflow to be healthy before logging its first run.

❀️ healthcheck
A command Compose runs inside a container to determine if it's truly ready (not just started). MLflow's /health endpoint is perfect for this.


Project File Structure

Here's how your Iris MLOps project directory will look by the end of Day 13. Everything lives under one root folder and is committed together.

iris-mlops/                       # Git repo root (from Days 1–12)
β”œβ”€β”€ docker-compose.yml            # ← NEW: orchestrates both services
β”œβ”€β”€ .env                          # ← NEW: env vars (never commit secrets)
β”œβ”€β”€ .dockerignore                 # shared ignore rules
β”‚
β”œβ”€β”€ trainer/                      # training service
β”‚   β”œβ”€β”€ Dockerfile                # production Dockerfile from Day 12
β”‚   β”œβ”€β”€ train.py                  # Iris training script (MLflow-enabled)
β”‚   β”œβ”€β”€ requirements.txt
β”‚   └── data/
β”‚       └── iris.csv              # raw data (or use sklearn.datasets)
β”‚
# MLflow data lives in the mlflow_data and mlflow_artifacts
# named volumes, not in the repo (see Volume Management)
βœ… Reuse your Day 12 Dockerfile
The production Dockerfile you built on Day 12 is exactly what goes inside trainer/Dockerfile. Docker Compose builds it β€” you don't need to push to a registry. Just point build: ./trainer and Compose handles the rest.

The .env File

Keep tuneable values outside the YAML. Compose automatically loads .env from the same directory as your docker-compose.yml.

.env

# ─── MLflow Server ────────────────────────────────────────
MLFLOW_IMAGE=ghcr.io/mlflow/mlflow:2.14.1
MLFLOW_PORT=5000
MLFLOW_HOST=0.0.0.0
MLFLOW_BACKEND_STORE=sqlite:////mlflow/mlflow.db
MLFLOW_ARTIFACT_ROOT=/artifacts

# ─── Trainer ──────────────────────────────────────────────
MLFLOW_TRACKING_URI=http://mlflow:5000
MLFLOW_EXPERIMENT_NAME=iris-compose-day13

# ─── Model Hyperparameters ────────────────────────────────
N_ESTIMATORS=100
MAX_DEPTH=5
TEST_SIZE=0.2
RANDOM_STATE=42
⚠️ Never commit .env to Git
Add .env to your .gitignore. Use a .env.example file with placeholder values as a template for teammates. For production, use Docker Secrets or your cloud provider's secret manager instead.

Writing the docker-compose.yml

Let's build the file piece by piece, then see the complete version. Every key is annotated so you know exactly what it does.

The MLflow Tracking Server Service

docker-compose.yml

services:

  mlflow:
    image: ${MLFLOW_IMAGE}              # pulled from .env
    container_name: iris_mlflow           # friendly name for docker ps
    restart: unless-stopped              # auto-restart if it crashes

    ports:
      - "${MLFLOW_PORT}:5000"             # HOST:CONTAINER β€” exposes UI to browser

    volumes:
      - mlflow_data:/mlflow              # SQLite DB + run metadata persist here
      - mlflow_artifacts:/artifacts      # model files and artifacts persist here

    environment:
      MLFLOW_BACKEND_STORE_URI: ${MLFLOW_BACKEND_STORE}
      MLFLOW_ARTIFACT_ROOT: ${MLFLOW_ARTIFACT_ROOT}

    # Compose fills ${...} from .env; no shell runs here to expand $VARS
    command: >-                           # YAML block scalar β€” single long line
      mlflow server
      --backend-store-uri ${MLFLOW_BACKEND_STORE}
      --artifacts-destination ${MLFLOW_ARTIFACT_ROOT}
      --serve-artifacts
      --host ${MLFLOW_HOST}
      --port 5000

    healthcheck:
      test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:5000/health')"]  # no curl in this image
      interval: 10s                       # check every 10 seconds
      timeout: 5s                         # fail if no response in 5s
      retries: 5                          # mark unhealthy after 5 failures
      start_period: 15s                   # grace period on first start

    networks:
      - ml_network

The Trainer Service

docker-compose.yml β€” trainer service

  trainer:
    build:
      context: ./trainer                  # directory containing Dockerfile
      dockerfile: Dockerfile              # explicit (useful when you have multiples)
      args:                               # passed to ARG in Dockerfile at build time
        PYTHON_VERSION: "3.11"
    container_name: iris_trainer

    depends_on:
      mlflow:
        condition: service_healthy        # wait for MLflow healthcheck to pass

    environment:
      MLFLOW_TRACKING_URI: ${MLFLOW_TRACKING_URI}
      MLFLOW_EXPERIMENT_NAME: ${MLFLOW_EXPERIMENT_NAME}
      N_ESTIMATORS: ${N_ESTIMATORS}
      MAX_DEPTH: ${MAX_DEPTH}
      TEST_SIZE: ${TEST_SIZE}
      RANDOM_STATE: ${RANDOM_STATE}

    volumes:
      - ./trainer:/app                    # bind mount: live-edit code without rebuild
      - mlflow_artifacts:/artifacts       # share artifact store with mlflow container

    networks:
      - ml_network

Networks and Volumes declarations

docker-compose.yml β€” networks & volumes

networks:
  ml_network:
    driver: bridge                       # default for local dev; isolated from host
    name: iris_ml_network                 # deterministic name (no random prefix)

volumes:
  mlflow_data:                           # SQLite DB, run metadata, tags
    driver: local
  mlflow_artifacts:                      # models, plots, confusion matrices
    driver: local
πŸ’‘
 Bind Mount vs Named Volume

Bind mount (./trainer:/app) links a host directory to the container. Changes you make in your editor appear inside the container immediately β€” perfect for iterative development.

Named volume (mlflow_data:/mlflow) is Docker-managed storage with no host path. It survives docker compose down but is removed by docker compose down -v. Use named volumes for database files and artifacts you want to persist.

The Complete File

docker-compose.yml

# ─── iris-mlops/docker-compose.yml ────────────────────────────────────────
# Day 13: Multi-Service ML Environment
# Usage: docker compose up --build
# ──────────────────────────────────────────────────────────────────────────

name: iris_mlops

services:

  # ── MLflow Tracking Server ─────────────────────────────────────────────
  mlflow:
    image: ${MLFLOW_IMAGE}
    container_name: iris_mlflow
    restart: unless-stopped

    ports:
      - "${MLFLOW_PORT}:5000"

    volumes:
      - mlflow_data:/mlflow
      - mlflow_artifacts:/artifacts

    environment:
      MLFLOW_BACKEND_STORE_URI: ${MLFLOW_BACKEND_STORE}
      MLFLOW_ARTIFACT_ROOT: ${MLFLOW_ARTIFACT_ROOT}

    command: >
      mlflow server
      --backend-store-uri ${MLFLOW_BACKEND_STORE}
      --artifacts-destination ${MLFLOW_ARTIFACT_ROOT}
      --serve-artifacts
      --host ${MLFLOW_HOST}
      --port 5000

    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

    networks:
      - ml_network

  # ── Training Service ───────────────────────────────────────────────────
  trainer:
    build:
      context: ./trainer
      dockerfile: Dockerfile
      args:
        PYTHON_VERSION: "3.11"
    container_name: iris_trainer

    depends_on:
      mlflow:
        condition: service_healthy

    environment:
      MLFLOW_TRACKING_URI: ${MLFLOW_TRACKING_URI}
      MLFLOW_EXPERIMENT_NAME: ${MLFLOW_EXPERIMENT_NAME}
      N_ESTIMATORS: ${N_ESTIMATORS}
      MAX_DEPTH: ${MAX_DEPTH}
      TEST_SIZE: ${TEST_SIZE}
      RANDOM_STATE: ${RANDOM_STATE}

    volumes:
      - ./trainer:/app
      - mlflow_artifacts:/artifacts

    networks:
      - ml_network

# ── Network ────────────────────────────────────────────────────────────
networks:
  ml_network:
    driver: bridge
    name: iris_ml_network

# ── Volumes ────────────────────────────────────────────────────────────
volumes:
  mlflow_data:
    driver: local
  mlflow_artifacts:
    driver: local

The Training Script

The Python script running inside the trainer container. It reads hyperparameters from environment variables (injected by Compose), trains on Iris, logs everything to MLflow via the tracking URI DNS name.

trainer/train.py

#!/usr/bin/env python3
"""
Day 13 β€” Iris Classifier that logs to an MLflow server
running in a sibling Docker container via Compose.
"""
import os
import logging
import mlflow
import mlflow.sklearn
import numpy as np
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, f1_score, classification_report
from sklearn.preprocessing import label_binarize

logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
log = logging.getLogger(__name__)


def load_config() -> dict:
    """Read hyperparameters from env vars set by Docker Compose."""
    return {
        "n_estimators": int(os.environ.get("N_ESTIMATORS", 100)),
        "max_depth":    int(os.environ.get("MAX_DEPTH", 5)),
        "test_size":    float(os.environ.get("TEST_SIZE", 0.2)),
        "random_state": int(os.environ.get("RANDOM_STATE", 42)),
    }


def train(cfg: dict):
    # ── Tracking setup ────────────────────────────────────────────────────
    tracking_uri  = os.environ["MLFLOW_TRACKING_URI"]    # http://mlflow:5000
    experiment    = os.environ.get("MLFLOW_EXPERIMENT_NAME", "iris-compose")

    mlflow.set_tracking_uri(tracking_uri)
    mlflow.set_experiment(experiment)
    log.info(f"Tracking URI  : {tracking_uri}")
    log.info(f"Experiment    : {experiment}")

    # ── Data ──────────────────────────────────────────────────────────────
    iris        = datasets.load_iris()
    X_train, X_test, y_train, y_test = train_test_split(
        iris.data, iris.target,
        test_size=cfg["test_size"],
        random_state=cfg["random_state"],
        stratify=iris.target,
    )

    with mlflow.start_run() as run:
        log.info(f"MLflow run id : {run.info.run_id}")

        # ── Log hyperparams ───────────────────────────────────────────────
        mlflow.log_params(cfg)
        mlflow.set_tags({
            "model_type": "RandomForest",
            "dataset":    "iris",
            "day":        "13",
            "source":     "docker-compose",
        })

        # ── Train ─────────────────────────────────────────────────────────
        model = RandomForestClassifier(
            n_estimators=cfg["n_estimators"],
            max_depth=cfg["max_depth"],
            random_state=cfg["random_state"],
        )
        model.fit(X_train, y_train)

        # ── Evaluate ──────────────────────────────────────────────────────
        y_pred    = model.predict(X_test)
        accuracy  = accuracy_score(y_test, y_pred)
        f1_macro  = f1_score(y_test, y_pred, average="macro")
        f1_weighted = f1_score(y_test, y_pred, average="weighted")

        mlflow.log_metrics({
            "accuracy":    accuracy,
            "f1_macro":    f1_macro,
            "f1_weighted": f1_weighted,
            "n_features":  X_train.shape[1],
            "train_size":  X_train.shape[0],
            "test_size":   X_test.shape[0],
        })

        log.info(f"Accuracy      : {accuracy:.4f}")
        log.info(f"F1 (macro)    : {f1_macro:.4f}")

        # ── Log model ─────────────────────────────────────────────────────
        signature = mlflow.models.infer_signature(X_train, model.predict(X_train))
        mlflow.sklearn.log_model(
            model,
            artifact_path="random_forest_model",
            signature=signature,
            registered_model_name="iris-rf-compose",
        )

        # ── Log classification report as artifact ─────────────────────────
        report = classification_report(y_test, y_pred, target_names=iris.target_names)
        mlflow.log_text(report, "classification_report.txt")

        log.info("Run complete. Model registered as 'iris-rf-compose'.")


if __name__ == "__main__":
    config = load_config()
    log.info(f"Config: {config}")
    train(config)

The Trainer Dockerfile

This is your Day 12 production Dockerfile, slightly adapted. Note how it uses an ARG for the Python version so Docker Compose can pass it in at build time.

trainer/Dockerfile

# ─── Stage 1: dependency builder ─────────────────────────────────────────
ARG PYTHON_VERSION=3.11
FROM python:${PYTHON_VERSION}-slim-bookworm AS builder

WORKDIR /build

# System deps for scikit-learn compilation
RUN apt-get update && apt-get install -y --no-install-recommends \
        gcc g++ && \
    rm -rf /var/lib/apt/lists/*

COPY requirements.txt .
RUN pip install --upgrade pip && \
    pip install --no-cache-dir --prefix=/install -r requirements.txt


# ─── Stage 2: runtime ────────────────────────────────────────────────────
FROM python:${PYTHON_VERSION}-slim-bookworm

# Non-root user for security
RUN groupadd -r mluser && useradd -r -g mluser mluser

WORKDIR /app

# Copy installed packages from builder
COPY --from=builder /install /usr/local

# Copy application code
COPY --chown=mluser:mluser . .

# Create artifacts mount point
RUN mkdir -p /artifacts && chown -R mluser:mluser /artifacts

USER mluser

# Default command β€” runs training and exits
CMD ["python", "train.py"]

trainer/requirements.txt

scikit-learn==1.5.1
mlflow==2.14.1
numpy==1.26.4
pandas==2.2.2

Service Startup Lifecycle

Understanding when each container starts and what triggers the next step is critical for reliable ML pipelines.

Compose creates network and volumes, starts mlflow, polls /health until healthy, then builds and starts the trainer, which logs to mlflow:5000 and exits 0.
Startup sequence: Compose waits for MLflow's healthcheck before launching the trainer
⚠️ depends_on without healthcheck = race condition
Using depends_on: mlflow alone only waits for the container to start, not for MLflow to be ready. MLflow takes several seconds to initialise its SQLite DB. Without condition: service_healthy, your trainer will fail with a connection error. Always pair depends_on with a healthcheck.

Running the Stack

A full reference of the Compose commands you'll use daily. Master these and you'll never need to manage individual containers again.

CommandWhat it doesWhen to use
docker compose up --buildBuild images and start all services β€” attaches logs to terminalFirst run, or after code changes
docker compose up -d --buildSame as above but detached (runs in background)Day-to-day usage once you trust the config
docker compose logs -fFollow all service logs in real timeDebugging / monitoring training progress
docker compose logs -f trainerFollow logs for trainer onlyWatching a specific service
docker compose ps -aShow status of all services (running, exited, health)Quick health check
docker compose exec mlflow bashOpen a shell inside the running mlflow containerInspecting the SQLite DB or file system
docker compose run --rm trainer python train.pyRun training once without the full stack (ad-hoc)Quickly test a script change
docker compose downStop and remove containers and networks (volumes kept)End of work session β€” data persists
docker compose down -vStop everything and delete named volumes β€” clean slateReset experiment data, debug fresh start
docker compose configPrint the resolved YAML (with .env interpolated)Verify env var substitution is correct
cd iris-mlops
docker compose up --build

Open http://localhost:5000 in your browser. You should see the MLflow UI with the iris-compose-day13 experiment and a completed run.


Networking

How does http://mlflow:5000 work inside the trainer container? Let's demystify Docker's embedded DNS.

The trainer asks Docker DNS at 127.0.0.11 for mlflow, gets 172.20.0.2, then calls port 5000 there and gets OK.
Docker's embedded DNS server (127.0.0.11) resolves service names to container IPs

verify DNS resolution from inside the trainer container

# The trainer exits after training, so start a fresh one with "run" (not "exec").
# The slim image has no nslookup or curl, so ask Python instead.
docker compose run --rm trainer python -c "import socket; print(socket.gethostbyname('mlflow'))"
# 172.20.0.2

docker compose run --rm trainer python -c "import urllib.request; print(urllib.request.urlopen('http://mlflow:5000/health').read().decode())"
# OK

Volume Management

Volumes are where your experiment data lives. Understanding what persists where prevents nasty surprises.

./trainer is bind-mounted at /app in the trainer; mlflow_data and mlflow_artifacts named volumes mount at /mlflow and /artifacts in the mlflow container.
Bind mounts link your local code; named volumes persist ML data across restarts

inspect volumes

docker volume ls --filter name=iris

Running Multiple Experiments

The real power of this setup: run the trainer with different hyperparameters by overriding env vars, with MLflow logging every run to the same persistent server.

# Run 1: Baseline

$ docker compose run --rm trainer python train.py

iris_trainer | Accuracy: 0.9667


# Run 2: Deeper Trees

$ N_ESTIMATORS=200 MAX_DEPTH=10 docker compose run --rm trainer python train.py

iris_trainer | Accuracy: 0.9667


# Run 3: Shallow, Faster Model

$ N_ESTIMATORS=50 MAX_DEPTH=3 docker compose run --rm trainer python train.py

iris_trainer | Accuracy: 0.9333


# View All Experiment Runs

All three experiment runs are visible in the MLflow UI:

http://localhost:5000


# Verify Running Services

$ docker compose ps -a

NAME            IMAGE                              COMMAND         STATUS                 PORTS
iris_mlflow     ghcr.io/mlflow/mlflow:2.14.1       "mlflow..."    Up (healthy)          0.0.0.0:5000->5000/tcp
iris_trainer    iris_mlops-trainer                 "python..."    Exited (0)
βœ… Shell variable override
Prefixing a docker compose run command with VAR=value overrides that variable for this single execution only. The .env file defaults are unchanged. This is a clean way to do quick hyperparameter sweeps without editing files.

Troubleshooting Common Issues

Things that go wrong when starting out, and exactly how to fix them.

SymptomRoot CauseFix
Connection refused: http://mlflow:5000Trainer started before MLflow was ready. Missing healthcheck condition.Add condition: service_healthy to depends_on. Check healthcheck is defined on mlflow service.
Trainer exits immediately with code 0Expected! The trainer runs to completion and exits. MLflow server stays up.This is normal behaviour. Run docker compose ps -a β€” trainer should show Exited (0).
Error: MLFLOW_TRACKING_URI not set.env file not found or variable missing.Run docker compose config to verify env interpolation. Ensure .env is in same dir as docker-compose.yml.
MLflow UI shows no experimentsTrainer logged to a different URI or experiment name.Check logs with docker compose logs trainer. Verify MLFLOW_EXPERIMENT_NAME and MLFLOW_TRACKING_URI.
Port 5000 already in useAnother process (e.g. macOS Control Center) is bound to 5000.Change MLFLOW_PORT=5001 in .env, then access at localhost:5001.
PermissionError writing artifactsNon-root user in container can't write to volume mount path.Ensure RUN mkdir -p /artifacts && chown -R mluser:mluser /artifacts is in your Dockerfile.
Image not rebuilding after code changeDocker cache. Using up -d without --build.Use docker compose up --build or docker compose build --no-cache trainer.

Key Concepts Quick Reference

Compose KeyTypeWhat it controlsML Use Case
image:ServicePull a pre-built image from a registryMLflow server, Postgres, MinIO
build:ServiceBuild a local Dockerfile into an imageTraining containers, custom preprocessing services
ports:ServiceMap host port β†’ container portMLflow UI (:5000), Jupyter (:8888), FastAPI (:8000)
volumes:ServiceMount host dirs or named volumes into containersPersist experiment DB, share artifact store
environment:ServiceInject env vars into the containerTracking URI, hyperparams, API keys
depends_on:ServiceDeclare startup ordering + health conditionsTrainer waits for MLflow; API waits for DB
healthcheck:ServiceDefine readiness probe for the containerMLflow /health, Postgres TCP check
restart:ServiceRestart policy on failureunless-stopped for MLflow server
networks: (service)ServiceAttach service to one or more networksIsolate training from serving traffic
networks: (top-level)GlobalDefine custom networks with driver settingsml_network, serving_network
volumes: (top-level)GlobalDeclare named volumes for the projectmlflow_data, mlflow_artifacts

Docker Compose is the bridge between isolated ML components and a fully integrated local MLOps platform. By defining your entire development environment as code, you ensure every engineer works with the same reproducible setup.

This reduces configuration drift, speeds up experimentation, and makes debugging significantly easier.

The skills you build with Docker Compose translate directly to production orchestration concepts used in modern cloud-native platforms. Mastering it is a foundational step toward building reliable, scalable, and production-ready MLOps systems.


⚑ Quick Reference

Keep the momentum going β€” everything you need on LearnXOps in one place:

Share this post