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:
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.
1Set MONGODB_URI With Service Hostname "mongodb" and authSource=admin
.envUse 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.
.envdotenvNODE_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"2Connect Mongoose Cleanly With Graceful SIGTERM Shutdown
src/db.tsConnect 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.tstypescriptimport 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); }); }3Start the Stack and Verify mongosh Healthcheck Status
terminalBuild and boot the Compose stack, then verify mongodb reports (healthy) before sending test requests to Express.
terminalbashdocker compose up -d --build docker compose ps docker compose logs -f api4Verify Persistent Collections Using mongosh Inside the Container
terminalInspect databases directly via docker compose exec without publishing port 27017 publicly.
terminalbashdocker 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.
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.
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.
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.
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:
Validate Node.js dotenv and native --env-file .env configs in your browser. Fix unquoted # truncation, duplicate keys, multiline PEM keys, and NODE_ENV bugs.
Generate a production Nginx reverse proxy for Node.js Express and PM2 on port 4000 with trust proxy, real client IP headers, Certbot SSL, and rate-limit safety.
Resolve CORS preflight errors between Node.js Express APIs and React Vite on port 5173. Generate cors() configs, fix PATCH/DELETE methods, and debug 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.
Related Docker Compose Stack Guides
Browse all 10 Compose stacks →Docker Compose Node.js + BullMQ Worker + Redis 7 + PostgreSQL 16 Guide
Generate a Docker Compose config for Node.js APIs, BullMQ background workers, Redis 7, and PostgreSQL 16 with native healthchecks and noeviction Redis safety.
Docker Compose Next.js Standalone + Prisma + PostgreSQL 16 Stack Guide
Generate a Docker Compose config for Next.js App Router standalone output with Prisma ORM and PostgreSQL 16 using pg_isready healthchecks and service DNS.
Docker Compose FastAPI + PostgreSQL 16 + Celery Worker Healthcheck Guide
Build a production Docker Compose stack for Python FastAPI, PostgreSQL 16, Redis 7, and Celery workers with pg_isready healthchecks and Alembic migrations.
Docker Compose Laravel + MySQL 8 + Redis Queue Stack & Healthcheck Guide
Generate a production Docker Compose file for Laravel 11/12 with MySQL 8, Redis 7, and queue:work using mysqladmin and redis-cli service_healthy probes.