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:
- π Courses β Video courses & AI-built courses
- π Ebooks β Community ebooks & your own
- π§ͺ All Labs & Challenges β DevOps, Cloud, SRE & more
- βΈοΈ Kubernetes Labs & Playground β kind clusters, playground & challenges
- π€ AI Agent & Bot Labs β OpenClaw Β· Hermes Β· CrewAI Β· LangGraph Β· MCP
π Key Learnings
- Why Docker Compose for ML?
- Architecture: What We're Building
- Docker Compose Core Concepts
- Project File Structure
- The
.envFile - 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.

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.

π§ 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 insidetrainer/Dockerfile. Docker Compose builds it β you don't need to push to a registry. Just pointbuild: ./trainerand 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.envto your.gitignore. Use a.env.examplefile 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_networkThe 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: localBind 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: localThe 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.2Service Startup Lifecycle
Understanding when each container starts and what triggers the next step is critical for reliable ML pipelines.

β οΈ depends_on without healthcheck = race condition
Usingdepends_on: mlflowalone only waits for the container to start, not for MLflow to be ready. MLflow takes several seconds to initialise its SQLite DB. Withoutcondition: service_healthy, your trainer will fail with a connection error. Always pairdepends_onwith ahealthcheck.
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.
| Command | What it does | When to use |
|---|---|---|
docker compose up --build | Build images and start all services β attaches logs to terminal | First run, or after code changes |
docker compose up -d --build | Same as above but detached (runs in background) | Day-to-day usage once you trust the config |
docker compose logs -f | Follow all service logs in real time | Debugging / monitoring training progress |
docker compose logs -f trainer | Follow logs for trainer only | Watching a specific service |
docker compose ps -a | Show status of all services (running, exited, health) | Quick health check |
docker compose exec mlflow bash | Open a shell inside the running mlflow container | Inspecting the SQLite DB or file system |
docker compose run --rm trainer python train.py | Run training once without the full stack (ad-hoc) | Quickly test a script change |
docker compose down | Stop and remove containers and networks (volumes kept) | End of work session β data persists |
docker compose down -v | Stop everything and delete named volumes β clean slate | Reset experiment data, debug fresh start |
docker compose config | Print the resolved YAML (with .env interpolated) | Verify env var substitution is correct |
cd iris-mlops
docker compose up --buildOpen 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.

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())"
# OKVolume Management
Volumes are where your experiment data lives. Understanding what persists where prevents nasty surprises.

inspect volumes
docker volume ls --filter name=irisRunning 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 adocker compose runcommand withVAR=valueoverrides that variable for this single execution only. The.envfile 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.
| Symptom | Root Cause | Fix |
|---|---|---|
Connection refused: http://mlflow:5000 | Trainer 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 0 | Expected! 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 experiments | Trainer 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 use | Another process (e.g. macOS Control Center) is bound to 5000. | Change MLFLOW_PORT=5001 in .env, then access at localhost:5001. |
PermissionError writing artifacts | Non-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 change | Docker cache. Using up -d without --build. | Use docker compose up --build or docker compose build --no-cache trainer. |
Key Concepts Quick Reference
| Compose Key | Type | What it controls | ML Use Case |
|---|---|---|---|
image: | Service | Pull a pre-built image from a registry | MLflow server, Postgres, MinIO |
build: | Service | Build a local Dockerfile into an image | Training containers, custom preprocessing services |
ports: | Service | Map host port β container port | MLflow UI (:5000), Jupyter (:8888), FastAPI (:8000) |
volumes: | Service | Mount host dirs or named volumes into containers | Persist experiment DB, share artifact store |
environment: | Service | Inject env vars into the container | Tracking URI, hyperparams, API keys |
depends_on: | Service | Declare startup ordering + health conditions | Trainer waits for MLflow; API waits for DB |
healthcheck: | Service | Define readiness probe for the container | MLflow /health, Postgres TCP check |
restart: | Service | Restart policy on failure | unless-stopped for MLflow server |
networks: (service) | Service | Attach service to one or more networks | Isolate training from serving traffic |
networks: (top-level) | Global | Define custom networks with driver settings | ml_network, serving_network |
volumes: (top-level) | Global | Declare named volumes for the project | mlflow_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:
- π Courses β Video courses & AI-built courses
- π Ebooks β Community ebooks & your own
- π§ͺ All Labs & Challenges β DevOps, Cloud, SRE & more
- βΈοΈ Kubernetes Labs & Playground β kind clusters, playground & challenges
- π€ AI Agent & Bot Labs β OpenClaw Β· Hermes Β· CrewAI Β· LangGraph Β· MCP

Member discussion