composebuilder

Docker Compose: FastAPI + MongoDB 7 + Mongo Express

Docker Compose stack for a Python FastAPI API on MongoDB 7 with authentication, a healthcheck, persistent storage and a protected Mongo Express UI on localhost.

When to use this stack

FastAPI is a modern Python web framework that generates request validation and interactive API documentation from type hints. Paired with MongoDB, it gives you a quick path from an idea to a working JSON API, because documents can be stored in the same shape the endpoints return. This stack runs three containers: the FastAPI service built from a small Dockerfile, a MongoDB 7 server with root authentication and a healthcheck, and Mongo Express for browsing the data. The sample endpoints create and list items, which is enough to confirm the whole path works end to end.

Use this stack when you are prototyping an API, building an internal tool, or need a document store behind a Python service on a single server. It also suits projects whose data changes shape frequently. Do not treat the sample code as production ready. It has no authentication on the endpoints, no input limits and no indexes. Before real users arrive, add authentication, validate payloads with explicit models, and plan backups. Only the API and the admin UI are published, and both bind to 127.0.0.1. The database port is not published at all, so it stays on the Compose network.

docker-compose.yml

services:
  mongodb:
    image: mongo:7
    restart: unless-stopped
    environment:
      MONGO_INITDB_ROOT_USERNAME: ${MONGO_INITDB_ROOT_USERNAME}
      MONGO_INITDB_ROOT_PASSWORD: ${MONGO_INITDB_ROOT_PASSWORD}
      MONGO_INITDB_DATABASE: ${MONGO_INITDB_DATABASE}
    volumes:
      - mongo_data:/data/db
    healthcheck:
      test: ["CMD", "mongosh", "--quiet", "--eval", "db.adminCommand('ping')"]
      interval: 10s
      timeout: 5s
      retries: 5
      start_period: 20s

  api:
    build: ./api
    restart: unless-stopped
    environment:
      MONGO_URL: "mongodb://${MONGO_INITDB_ROOT_USERNAME}:${MONGO_INITDB_ROOT_PASSWORD}@mongodb:27017/?authSource=admin"
      MONGO_DB: ${MONGO_INITDB_DATABASE}
    ports:
      - "127.0.0.1:8000:8000"
    depends_on:
      mongodb:
        condition: service_healthy

  mongo-express:
    image: mongo-express:1.0.2
    restart: unless-stopped
    environment:
      ME_CONFIG_MONGODB_URL: "mongodb://${MONGO_INITDB_ROOT_USERNAME}:${MONGO_INITDB_ROOT_PASSWORD}@mongodb:27017/?authSource=admin"
      ME_CONFIG_MONGODB_ENABLE_ADMIN: "true"
      ME_CONFIG_BASICAUTH_ENABLED: "true"
      ME_CONFIG_BASICAUTH_USERNAME: ${MONGO_EXPRESS_USER}
      ME_CONFIG_BASICAUTH_PASSWORD: ${MONGO_EXPRESS_PASSWORD}
    ports:
      - "127.0.0.1:8081:8081"
    depends_on:
      mongodb:
        condition: service_healthy

volumes:
  mongo_data:

.env

.env
# Root account created on the first start of the data volume
# Use only letters and digits in the passwords, or URL-encode them inside the connection strings
MONGO_INITDB_ROOT_USERNAME=root_admin
MONGO_INITDB_ROOT_PASSWORD=CHANGE_ME_MONGO_ROOT_PASSWORD
MONGO_INITDB_DATABASE=app_db

# Web login for the Mongo Express interface
MONGO_EXPRESS_USER=ui_admin
MONGO_EXPRESS_PASSWORD=CHANGE_ME_MONGO_EXPRESS_PASSWORD

Start and verify

Create the small API project next to docker-compose.yml, then start the stack. The heredocs below write a Dockerfile, the Python dependencies and a minimal FastAPI app with three routes: health, create and list.

Shell
mkdir -p api
cat > api/Dockerfile <<'EOF'
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
EOF
cat > api/requirements.txt <<'EOF'
fastapi==0.115.5
uvicorn==0.32.1
pymongo==4.10.1
EOF
cat > api/main.py <<'EOF'
import os

from fastapi import FastAPI
from pymongo import MongoClient

client = MongoClient(os.environ["MONGO_URL"], serverSelectionTimeoutMS=5000)
db = client[os.environ["MONGO_DB"]]
app = FastAPI()


@app.get("/health")
def health():
    client.admin.command("ping")
    return {"status": "ok"}


@app.post("/items")
def create_item(item: dict):
    result = db.items.insert_one(item)
    return {"id": str(result.inserted_id)}


@app.get("/items")
def list_items():
    return [{**doc, "_id": str(doc["_id"])} for doc in db.items.find().limit(50)]
EOF
set -a; . ./.env; set +a
docker compose config --quiet
docker compose up -d --build
docker compose ps
docker compose logs --tail=50 mongodb
curl -s http://127.0.0.1:8000/health
curl -s -X POST http://127.0.0.1:8000/items -H "Content-Type: application/json" -d '{"name":"first"}'
curl -s http://127.0.0.1:8000/items
curl -s -o /dev/null -w "Mongo Express HTTP status: %{http_code}\n" -u "$MONGO_EXPRESS_USER:$MONGO_EXPRESS_PASSWORD" http://127.0.0.1:8081/

The health call should return {"status":"ok"}, the create call returns an id, and the list call shows the stored document.

Production checklist

  • Replace every CHANGE_ME value with a long random password, and keep the root account for administration only.
  • Create an application user with readWrite rights on app_db, and point MONGO_URL at that user.
  • Add authentication to the FastAPI routes and validate payloads with explicit Pydantic models instead of a plain dict.
  • Keep port 27017 unpublished, and put the API behind a TLS reverse proxy before it faces the internet.
  • Add indexes for the fields you query, and check slow queries with explain before shipping new features.
  • Set memory limits on the containers, and cap the WiredTiger cache if the host has little RAM.
  • Schedule mongodump or filesystem snapshot backups, store them off the server, and test a restore.
  • Pin the Python dependencies, and rebuild the image when security updates are released.

Common problems

  • Symptom: the API logs an authentication failed error. Cause: the connection string does not include authSource=admin, or the password differs from .env. Fix: check MONGO_URL in docker compose config and make sure it includes authSource=admin.

  • Symptom: the api container exits with a KeyError about MONGO_URL or MONGO_DB. Cause: the variable is missing or .env is not in the project folder. Fix: run docker compose config and confirm the resolved values before starting again.

  • Symptom: the root password in .env was changed, but the login still fails. Cause: MONGO_INITDB_ROOT_PASSWORD is applied only when the data volume is first created. Fix: change the password inside MongoDB with a user management command, or remove the volume if its data is disposable.

  • Symptom: Mongo Express shows ECONNREFUSED or cannot find the server. Cause: the connection host is wrong or MongoDB is not healthy yet. Fix: keep the host name mongodb in ME_CONFIG_MONGODB_URL and wait until the mongodb service is healthy.

Variations

  • Async driver: replace pymongo with Motor and async route handlers when the API handles many concurrent requests.
  • Replica set: run mongod with a replica set name and initiate it once, which enables multi-document transactions for the API.
  • TLS in front of the API: add Caddy with automatic certificates and expose only ports 80 and 443 to the internet.

Questions

Why does the API connection string include authSource=admin?

The MongoDB image creates the root user in the admin database, so every login must authenticate against admin. Without this parameter the correct password is still rejected.

Should the API use the root account in production?

No. Create an application user with readWrite rights on its own database, and keep the root account for administration only. The sample uses root to keep the first start simple.

Why is Mongo Express limited to localhost?

With admin access enabled, the UI can read every database on the server. Keep it on 127.0.0.1 and reach it through an SSH tunnel, or place it behind a TLS proxy with its own access control.

Do I have to rebuild the image after editing main.py?

Yes. The code is copied into the image at build time, so run docker compose up -d --build api after each change. The MongoDB data is kept in its volume across rebuilds.

Adapt this stack

Load these files into the builder to rename services, change ports, add a cache or a proxy, and generate fresh passwords for the .env.

Open in builder
  • MongoDB 7 + Mongo Express Admin UI

    Docker Compose stack for MongoDB 7 with root authentication, a healthcheck and a named volume, plus Mongo Express 1.0.2 on localhost with its own web login.

    • mongodb
    • mongo-express
    Difficulty: Beginner
  • Meilisearch v1 + Python FastAPI Search API

    Docker Compose stack for Meilisearch v1 in production mode with a master key, a healthcheck and persistent data, plus a FastAPI search API on localhost.

    • meilisearch
    • api
    Difficulty: Intermediate
  • ClickHouse 25.8 Analytics Database

    Docker Compose stack for ClickHouse 25.8 with a dedicated user, a healthcheck, raised file limits and HTTP and native ports on localhost for analytical queries.

    • clickhouse
    Difficulty: Advanced
  • Elasticsearch 8 + Kibana Search Stack

    Docker Compose stack for Elasticsearch 8.19 and Kibana 8.19 with security enabled, a persistent volume, a healthcheck and localhost-only ports.

    • elasticsearch
    • kibana
    Difficulty: Advanced

Browse more Databases & Search stacks or the full library.