Docker Compose Builder · Node.js / Express + MongoDB

Docker Compose Node.js Express + MongoDB 7 Stack & Healthcheck Guide

Generate a Compose Specification docker-compose.yml and matching .env.example for Node.js / Express + MongoDB with native binary healthchecks, service_healthy boot ordering, and firewall-safe port bindings.

Written & verified by Chathura Prabashana · Updated November 2026

1. Adjust stack settings or load a test scenario2. Inspect live diagnostics3. Copy generated config
Quick-Test Scenarios:

1. Runtime & Data Services

2. Healthchecks, Workers & Security

# docker-compose.yml — Modern Compose Specification (no obsolete 'version:' attribute)
# Generated by OpsCheck DevTools (Node.js / Express)
name: express_mongo_stack

services:
  api:
    build:
      context: .
      dockerfile: Dockerfile
    restart: unless-stopped
    env_file:
      - .env
    ports:
      - "127.0.0.1:4000:4000"
    environment:
      DB_HOST: mongodb
      DB_PORT: "27017"
    depends_on:
      mongodb:
        condition: service_healthy
    networks:
      - app_network

  mongodb:
    image: mongo:7
    restart: unless-stopped
    environment:
      MONGO_INITDB_ROOT_USERNAME: ${DB_USERNAME:-app}
      MONGO_INITDB_ROOT_PASSWORD: ${DB_PASSWORD:-change_me_strong}
      MONGO_INITDB_DATABASE: ${DB_DATABASE:-app_db}
    # Kept strictly internal on app_network (prevents Docker iptables UFW bypass)
    expose:
      - "27017"
    volumes:
      - db_data:/data/db
    healthcheck:
      test: ["CMD", "mongosh", "--quiet", "--eval", "db.adminCommand('ping').ok"]
      interval: 10s
      timeout: 5s
      retries: 5
      start_period: 20s
    networks:
      - app_network

networks:
  app_network:
    driver: bridge

volumes:
  db_data:
Service Boot Orderbridge: app_network
mongodb(healthy)api

Healthcheck & Security Diagnostics

Compose Spec v2+
  • passStartup Race Condition Prevented (condition: service_healthy)

    api will wait until mongodb pass their native healthchecks before starting.

  • infoInternal Bridge DNS Hostnames (Never Use localhost Inside Containers)

    Connect over the shared app_network using Docker service names: DB_HOST=mongodb (port 27017). Inside the "api" container, 127.0.0.1/localhost points only to "api" itself and always refuses DB/broker connections.

  • passFirewall-Safe Port Exposure Enabled (127.0.0.1 / Internal expose:)

    Database and broker ports stay strictly isolated on app_network via expose:, and app ports bind to 127.0.0.1 so Docker never bypasses host UFW/nftables rules.

  • passNative Probe Binaries Used (mongosh --eval)

    Generated healthchecks invoke built-in service binaries rather than curl or wget, avoiding false "unhealthy" states in minimal Alpine and slim official images.

  • passPersistent Named Volumes Declared (db_data)

    Top-level named volumes preserve database tables and broker queues across container rebuilds and "docker compose down" (data is only removed if you pass -v).

Runs locally in your browser. Compose YAML and environment templates are generated client-side.

Typical Container Boot & Connection Error (Node.js / Express + MongoDB)

When depends_on lacks condition: service_healthy or internal service hostnames are misconfigured in .env, container logs typically surface this error during startup:

docker compose logs (Startup Failure)

MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017 — Could not connect to any servers in your MongoDB cluster.

Container Boot Ordering, Bridge DNS & Persistence for Node.js / Express + MongoDB

Running a Node.js Express API with Mongoose or the official MongoDB driver alongside a MongoDB 7 container in Docker Compose is fast to prototype; yet three MongoDB-specific container quirks cause the vast majority of startup crashes. First, MongoDB 7 removed the legacy mongo shell completely; older healthcheck snippets calling mongo --eval fail immediately with "executable file not found" and leave the container permanently unhealthy.

Second, when MONGO_INITDB_ROOT_USERNAME and MONGO_INITDB_ROOT_PASSWORD are set, MongoDB creates that root user inside the "admin" authentication database. Connecting from Express with mongodb://app:pass@mongodb:27017/app_db without appending ?authSource=admin triggers "MongoServerError: Authentication failed" even when the username and password are completely accurate.

Third, Mongoose's initial connection attempt can fail on cold boots if Express starts before mongod finishes initializing WiredTiger storage files on the db_data volume. Pairing mongo:7 with a native mongosh --quiet --eval "db.adminCommand('ping').ok" healthcheck and condition: service_healthy guarantees Express waits until MongoDB is genuinely accepting wire-protocol commands.

Keeping MongoDB port 27017 strictly internal via expose: ["27017"] on app_network is essential for security: exposed MongoDB instances on 0.0.0.0:27017 are among the most heavily scanned targets on the internet, and Docker's iptables rules bypass UFW firewalls whenever host ports are published without 127.0.0.1.

By combining persistent named volumes (db_data:/data/db), firewall-safe port bindings, and proper authSource=admin URIs, your Express + MongoDB Compose stack behaves deterministically across local development and single-node Linux VPS production hosts.

For reliable Express and MongoDB 7 container operations, audit container resource usage via docker stats and configure WiredTiger cache limits (--wiredTigerCacheSizeGB) when sharing a modest VPS with other Node.js services. Verifying mongosh ping healthchecks alongside persistent db_data volumes ensures routine image security patches (docker compose up -d --build api) never interrupt stored collections or drop authentication credentials.

Step-by-Step Node.js / Express + MongoDB Docker Compose Setup Guide

Follow each step below to pair the generated Compose file with accurate container DNS variables, safe database migrations, and zero-downtime restarts.

  1. 1Set MONGODB_URI With Service Hostname "mongodb" and authSource=admin

    .env

    Use the Docker Compose service name "mongodb" instead of localhost, and always include ?authSource=admin when authenticating with the root user created by MONGO_INITDB_ROOT_USERNAME.

    .envdotenv
    NODE_ENV=production
    APP_PORT=4000
    DB_DATABASE=app_db
    DB_USERNAME=app
    DB_PASSWORD=change_me_strong
    MONGODB_URI="mongodb://app:change_me_strong@mongodb:27017/app_db?authSource=admin"
  2. 2Connect Mongoose Cleanly With Graceful SIGTERM Shutdown

    src/db.ts

    Connect using process.env.MONGODB_URI and close the MongoDB connection pool cleanly on SIGTERM so docker compose down flushes pending writes without abrupt disconnects.

    src/db.tstypescript
    import mongoose from 'mongoose';
    
    export async function connectMongo() {
      const uri = process.env.MONGODB_URI;
      if (!uri) throw new Error('MONGODB_URI is required');
    
      await mongoose.connect(uri, {
        serverSelectionTimeoutMS: 10000,
      });
    
      process.on('SIGTERM', async () => {
        await mongoose.connection.close();
        process.exit(0);
      });
    }
  3. 3Start the Stack and Verify mongosh Healthcheck Status

    terminal

    Build and boot the Compose stack, then verify mongodb reports (healthy) before sending test requests to Express.

    terminalbash
    docker compose up -d --build
    docker compose ps
    docker compose logs -f api
  4. 4Verify Persistent Collections Using mongosh Inside the Container

    terminal

    Inspect databases directly via docker compose exec without publishing port 27017 publicly.

    terminalbash
    docker compose exec mongodb mongosh -u app -p change_me_strong --authenticationDatabase admin --eval "db.adminCommand('ping')"

Common Node.js / Express + MongoDB Docker Compose Pitfalls

Avoid these three container orchestration mistakes before deploying your Compose stack onto staging or production servers.

Pitfall 1

Using Legacy "mongo" Binary Instead of "mongosh" in MongoDB 7 Healthchecks

MongoDB 6+ and 7 removed the legacy mongo binary. Healthchecks copied from older tutorials fail silently with exit code 127 and prevent Express from ever starting under condition: service_healthy. Always use mongosh.

Pitfall 2

Forgetting ?authSource=admin in MONGODB_URI

MONGO_INITDB_ROOT_USERNAME creates the initial user inside the admin database, not inside app_db. Omitting ?authSource=admin produces immediate authentication failures in Mongoose and the Node MongoDB driver.

Pitfall 3

MongoDB 7 Failing on Older CPUs Without AVX Instructions

Official mongo:7 images require x86_64 CPUs with AVX support. On older virtualized VPS hypervisors lacking AVX, mongod exits immediately with SIGILL (exit code 132); check lscpu | grep avx on the host.

Related Tools

Pair Your Docker Compose Stack With .env Linting, Nginx TLS & CORS Checks

Validate your .env file for unescaped $$ interpolation or leaked secrets, configure Nginx DNS resolution, and verify cross-origin headers:

Frequently Asked Questions

Why does Mongoose still try to connect to 127.0.0.1:27017 inside Docker?
Either your .env file was not loaded into the container (check env_file: [.env]), or your Express code fell back to a hardcoded "mongodb://localhost:27017" default when MONGODB_URI was undefined. Inside Docker, the host must be "mongodb".
How do I enable MongoDB transactions (single-node replica set) in Docker Compose?
Multi-document ACID transactions require a replica set. Pass command: ["--replSet", "rs0", "--bind_ip_all"] to the mongodb service, run rs.initiate() once via mongosh, and append ?directConnection=true&replicaSet=rs0 to MONGODB_URI.
Why did changing MONGO_INITDB_ROOT_PASSWORD in .env not update my password?
MongoDB only evaluates MONGO_INITDB_* variables when initializing an empty /data/db volume for the very first time. Changing credentials on an existing volume requires updating the user via mongosh or recreating the volume cleanly.
Can I add Redis caching alongside Express and MongoDB?
Yes. Toggle Redis 7 in the Cache / Broker selector above to automatically wire a redis:7-alpine container with redis-cli ping healthchecks and REDIS_URL config.
Browse all 10 Compose stacks →