Mongo Docker Compose: The Complete Setup Guide for 2026
Disclosure: This post contains one or more links to providers we have a real, registered affiliate/referral relationship with. We may earn a commission at no extra cost to you if you sign up through them.
Running MongoDB in a container is one of the fastest ways to get a working development or staging database without touching a package manager or wrestling with system service files. A mongo docker compose setup lets you define the database, its volumes, its network, and its environment variables in a single declarative file, then bring the whole thing up or down with one command. This guide walks through a real, working configuration, explains the options that actually matter, and covers the mistakes that trip up most people the first time they try it.
Whether you’re spinning up a local instance for a Node.js app, provisioning a staging replica set, or just want a disposable database for testing, the patterns below apply. We’ll build the compose file piece by piece, then look at authentication, persistence, networking, backups, and troubleshooting.
Why Use Mongo Docker Compose Instead of a Manual Install
Installing MongoDB directly on a host means managing its systemd unit, its config file location, its log rotation, and its upgrade path independently of everything else on the machine. A mongo docker compose file replaces all of that with a single YAML document that lives next to your application code, gets checked into version control, and behaves identically on your laptop, your CI runner, and your production VPS.
The core benefits:
docker compose up and gets the exact same MongoDB version and configuration.docker compose down removes the container cleanly, and you can choose whether volumes survive.This isn’t unique to MongoDB — the same reasoning applies to Postgres Docker Compose and Redis Docker Compose setups, and if you’re choosing between a full install and a container in the first place, it’s worth reading up on Dockerfile vs Docker Compose to understand where each tool fits.
Building a Basic Mongo Docker Compose File
Start with the minimal version that gets a single MongoDB instance running with a named volume for persistence.
services:
mongo:
image: mongo:7
container_name: mongo_db
restart: unless-stopped
ports:
- "27017:27017"
environment:
MONGO_INITDB_ROOT_USERNAME: admin
MONGO_INITDB_ROOT_PASSWORD: changeme
volumes:
- mongo_data:/data/db
volumes:
mongo_data:
Bring it up with:
docker compose up -d
That’s a complete, working mongo docker compose stack. The mongo_data named volume ensures your data survives container restarts and even docker compose down (as long as you don’t pass -v). The official image comes from Docker Hub and is maintained upstream, so pinning a major version like mongo:7 rather than mongo:latest avoids surprise upgrades when you rebuild months later.
Choosing the Right Image Tag
Always pin to at least a major version tag. mongo:latest will silently pull a newer major release the next time you run docker compose pull, which can break your application if a driver-incompatible change ships. mongo:7 or mongo:7.0 gives you predictable behavior while still receiving patch updates within that line. Check the MongoDB documentation for the current supported version matrix before deciding which line to track long-term.
Exposing or Hiding the Port
The ports mapping in the example above exposes MongoDB on the host’s 27017, which is convenient for local development tools like MongoDB Compass or mongosh connecting from outside the container. In a production mongo docker compose deployment where only your application container needs access, omit the ports block entirely and rely on Docker’s internal network — the app container can still reach mongo:27017 by service name, but nothing outside the Docker host can.
Authentication and Security in Mongo Docker Compose
Never run MongoDB in production without authentication enabled. The MONGO_INITDB_ROOT_USERNAME and MONGO_INITDB_ROOT_PASSWORD environment variables shown above are only read the very first time the container initializes an empty data directory — changing them later has no effect until you wipe the volume, which is a common source of confusion.
A more robust pattern separates secrets from the compose file itself:
services:
mongo:
image: mongo:7
restart: unless-stopped
env_file:
- .env
volumes:
- mongo_data:/data/db
volumes:
mongo_data:
# .env
MONGO_INITDB_ROOT_USERNAME=admin
MONGO_INITDB_ROOT_PASSWORD=a-strong-generated-password
This keeps credentials out of version control if .env is gitignored. For a deeper look at handling variables this way, see this site’s guide on Docker Compose Env and the related guide on Docker Compose Environment Variables. If you need to manage credentials more formally — separate secret files mounted read-only rather than plain environment variables — the Docker Compose Secrets guide covers that pattern in detail, and it applies just as well to a mongo docker compose stack as it does to any other service.
Creating Application-Specific Users
Running everything as the root MongoDB user is bad practice once you move past local experimentation. Use an init script mounted into the container’s entrypoint directory to create a scoped user for your application on first boot:
services:
mongo:
image: mongo:7
restart: unless-stopped
environment:
MONGO_INITDB_ROOT_USERNAME: admin
MONGO_INITDB_ROOT_PASSWORD: changeme
volumes:
- mongo_data:/data/db
- ./init-mongo.js:/docker-entrypoint-initdb.d/init-mongo.js:ro
volumes:
mongo_data:
// init-mongo.js
db = db.getSiblingDB('app_db');
db.createUser({
user: 'app_user',
pwd: 'app_user_password',
roles: [{ role: 'readWrite', db: 'app_db' }]
});
Any .js or .sh file dropped into /docker-entrypoint-initdb.d/ runs automatically the first time the container initializes an empty /data/db directory, exactly like the equivalent mechanism in the official Postgres image.
Connecting an Application to Mongo Docker Compose
The real value of a mongo docker compose setup shows up when your application container joins the same Docker network and connects by service name instead of an IP address or localhost.
services:
app:
build: .
restart: unless-stopped
depends_on:
- mongo
environment:
MONGO_URI: mongodb://app_user:app_user_password@mongo:27017/app_db
ports:
- "3000:3000"
mongo:
image: mongo:7
restart: unless-stopped
environment:
MONGO_INITDB_ROOT_USERNAME: admin
MONGO_INITDB_ROOT_PASSWORD: changeme
volumes:
- mongo_data:/data/db
volumes:
mongo_data:
Here, mongo in the connection string resolves via Docker’s internal DNS to the database container — no port mapping to the host is even necessary for the app to reach it. depends_on controls startup order but does not wait for MongoDB to actually finish initializing, so your application code should still implement connection retry logic on boot, particularly for the very first container start when the database is creating its data files.
Health Checks for Reliable Startup
Because depends_on alone doesn’t guarantee MongoDB is ready to accept connections, add a health check so dependent services can wait for a real ready signal:
services:
mongo:
image: mongo:7
restart: unless-stopped
environment:
MONGO_INITDB_ROOT_USERNAME: admin
MONGO_INITDB_ROOT_PASSWORD: changeme
volumes:
- mongo_data:/data/db
healthcheck:
test: echo 'db.runCommand("ping").ok' | mongosh --quiet
interval: 10s
timeout: 5s
retries: 5
app:
build: .
depends_on:
mongo:
condition: service_healthy
volumes:
mongo_data:
With condition: service_healthy, Compose won’t start the app container until MongoDB’s health check passes, which eliminates a whole class of “connection refused on first boot” errors.
Debugging and Managing a Mongo Docker Compose Stack
Once the stack is running, a handful of commands cover almost everything you’ll need day to day.
# View live logs from the mongo service
docker compose logs -f mongo
# Open a mongosh shell inside the running container
docker compose exec mongo mongosh -u admin -p
# Check container status
docker compose ps
# Rebuild and restart after a compose file change
docker compose up -d --build
If logs aren’t giving you enough context, this site’s Docker Compose Logs guide and the related Docker Compose Logging article go deeper into log drivers and formatting options. And if you change the image version or add init scripts and need the container to pick up the changes cleanly, the Docker Compose Rebuild guide walks through the difference between restart, up --build, and a full down/up cycle.
Backing Up and Restoring Data
The named volume protects against container removal, but it doesn’t protect against disk failure or accidental docker volume rm. Use mongodump and mongorestore from inside the running container for portable backups:
# Backup
docker compose exec mongo mongodump --username admin --password changeme \
--authenticationDatabase admin --archive=/data/db/backup.archive
# Copy the archive out to the host
docker cp mongo_db:/data/db/backup.archive ./backup.archive
# Restore into a fresh container
docker cp ./backup.archive mongo_db:/data/db/backup.archive
docker compose exec mongo mongorestore --username admin --password changeme \
--authenticationDatabase admin --archive=/data/db/backup.archive
Schedule this as a cron job or an n8n workflow if you’re already running automation infrastructure — for teams doing broader workflow automation around their Docker stack, see n8n Self Hosted for a comparable containerized setup pattern.
Shutting Down Cleanly
When you’re done with a stack, understand the difference between stopping and removing it:
docker compose stop # stops containers, keeps volumes and networks
docker compose down # removes containers and networks, volumes persist
docker compose down -v # removes containers, networks, AND volumes (data loss)
The full breakdown of these options, including what happens to networks and orphaned containers, is covered in Docker Compose Down — worth reading before you run any of these in a shared environment, since -v is irreversible without a backup.
Where to Host Your Mongo Docker Compose Stack
For anything beyond local development, you’ll want a VPS with enough memory and disk I/O to handle MongoDB’s working set comfortably — MongoDB is memory-hungry by design since it memory-maps its data files for performance. A provider like DigitalOcean or Hetzner offers straightforward block-storage-backed instances that work well for a single-node or small replica-set mongo docker compose deployment. Whichever provider you choose, mount your data volume on a disk with predictable I/O rather than ephemeral storage, and monitor memory usage closely as your working set grows.
Recommended: Ready to put this into practice? DigitalOcean is a tool we use for exactly this, and we have a real, disclosed affiliate relationship with them.
FAQ
Does a mongo docker compose setup support replica sets?
Yes, but it requires additional configuration beyond a single service block — each replica set member needs its own service, a shared Docker network, and an rs.initiate() call once all members are reachable. For local development, a single-node deployment is usually sufficient; save the replica-set complexity for staging or production environments that need failover.
How do I change the MongoDB root password after the container has already initialized?
Environment variables like MONGO_INITDB_ROOT_PASSWORD only apply on first initialization of an empty data directory. To change credentials afterward, connect with mongosh and run db.changeUserPassword() against the admin database, or wipe the volume and reinitialize if you don’t need to preserve existing data.
Can I run MongoDB and my application in the same compose file as other databases?
Yes — Compose supports any number of services in one file. It’s common to see MongoDB alongside Redis for caching or Postgres for a different subsystem, all defined in the same docker-compose.yml and connected via the same internal network, each reachable by its own service name.
Why does my app container fail to connect to Mongo on the very first docker compose up?
MongoDB needs a few seconds to initialize its data files on a truly fresh volume, and depends_on alone doesn’t wait for that. Add a healthcheck block to the mongo service and use condition: service_healthy on the dependent service, or implement retry logic with backoff in your application’s database connection code.
Conclusion
A mongo docker compose file gives you a reproducible, version-controlled way to run MongoDB alongside your application, whether that’s a single local container or a multi-service stack with health checks and a dedicated application user. Start with the minimal image-plus-volume configuration, add authentication and an init script once you need scoped users, and layer in health checks and backup routines as the deployment moves from local development toward production. The same core patterns — named volumes for persistence, service-name networking, and environment-based secrets — carry over directly if you later add other containerized services like Postgres Docker Compose to the same stack. For the full range of official configuration options and image variants, the Docker Compose documentation is the authoritative reference to keep bookmarked.
Leave a Reply