MongoDB: Use Docker Compose for MongoDB
This is how to use Docker Compose to configure and start a container using MongoDB community server

"MongoDB is a source-available, cross-platform, document-oriented databaseprogram. Classified as a NoSQL database product, MongoDB uses JSON-like documents with optional schemas."
If you start a new project using MongoDB, or just want to test it, the easiest way is to use Docker for it.
In my case, I use MongoDB community server. This is my Docker Compose file:
services:
db:
image: mongodb/mongodb-community-server
environment:
- MONGO_INITDB_ROOT_USERNAME=root
- MONGO_INITDB_ROOT_PASSWORD=XxXxXxXx
ports:
- 27017:27017
Let's pull the image and start the container:
# docker compose pull
# docker compose up -d
[+] Pulling 1/1
✔ db Pulled 1.0s
[+] Running 1/1
✔ Container mongodb-db-1 Started
Then, we can have a look at the logs:
db-1 | Warning: File MONGO_INITDB_ROOT_USERNAME_FILE is deprecated. Use MONGODB_INITDB_ROOT_USERNAME_FILE instead.
db-1 | Warning: File MONGO_INITDB_ROOT_PASSWORD_FILE is deprecated. Use MONGODB_INITDB_ROOT_PASSWORD_FILE instead.
db-1 | about to fork child process, waiting until server is ready for connections.
db-1 | forked process: 10
db-1 |
db-1 | {"t":{"$date":"2025-02-01T14:49:10.426+00:00"},"s":"I", "c":"CONTROL", "id":20698, "ctx":"main","msg":"***** SERVER RESTARTED *****"}
db-1 | {"t":{"$date":"2025-02-01T14:49:10.440+00:00"},"s":"I", "c":"NETWORK", "id":4915701, "ctx":"main","msg":"Initialized wire specification","attr":{"spec":{"incomingExternalClient":{"minWireVersion":0,"maxWireVersion":21},"incomingInternalClient":{"minWireVersion":0,"maxWireVersion":21},"outgoing":{"minWireVersion":6,"maxWireVersion":21},"isInternalClient":true}}}
db-1 | {"t":{"$date":"2025-02-01T14:49:10.444+00:00"},"s":"I", "c":"CONTROL", "id":23285, "ctx":"main","msg":"Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none'"}
db-1 | {"t":{"$date":"2025-02-01T14:49:10.448+00:00"},"s":"I", "c":"NETWORK", "id":4648601, "ctx":"main","msg":"Implicit TCP FastOpen unavailable. If TCP FastOpen is required, set tcpFastOpenServer, tcpFastOpenClient, and tcpFastOpenQueueSize."}
db-1 | {"t":{"$date":"2025-02-01T14:49:10.455+00:00"},"s":"I", "c":"REPL", "id":5123008, "ctx":"main","msg":"Successfully registered PrimaryOnlyService","attr":{"service":"TenantMigrationDonorService","namespace":"config.tenantMigrationDonors"}}
db-1 | {"t":{"$date":"2025-02-01T14:49:10.455+00:00"},"s":"I", "c":"REPL", "id":5123008, "ctx":"main","msg":"Successfully registered PrimaryOnlyService","attr":{"service":"TenantMigrationRecipientService","namespace":"config.tenantMigrationRecipients"}}
db-1 | {"t":{"$date":"2025-02-01T14:49:10.456+00:00"},"s":"I", "c":"CONTROL", "id":5945603, "ctx":"main","msg":"Multi threading initialized"}
[...]
db-1 | {"t":{"$date":"2025-02-01T14:49:14.170+00:00"},"s":"I", "c":"CONTROL", "id":8423403, "ctx":"initandlisten","msg":"mongod startup complete","attr":{"Summary of time elapsed":{"Startup from clean shutdown?":true,"Statistics":{"Transport layer setup":"0 ms","Run initial syncer crash recovery":"0 ms","Create storage engine lock file in the data directory":"0 ms","Get metadata describing storage engine":"0 ms","Validate options in metadata against current startup options":"0 ms","Create storage engine":"1011 ms","Write current PID to file":"0 ms","Initialize FCV before rebuilding indexes":"6 ms","Drop abandoned idents and get back indexes that need to be rebuilt or builds that need to be restarted":"0 ms","Rebuild indexes for collections":"0 ms","Load cluster parameters from disk for a standalone":"0 ms","Build user and roles graph":"0 ms","Verify indexes for admin.system.users collection":"0 ms","Set up the background thread pool responsible for waiting for opTimes to be majority committed":"0 ms","Initialize information needed to make a mongod instance shard aware":"0 ms","Start up the replication coordinator":"2 ms","Start transport layer":"0 ms","_initAndListen total elapsed time":"1036 ms"}}}}
db-1 | {"t":{"$date":"2025-02-01T14:50:14.157+00:00"},"s":"I", "c":"WTCHKPT", "id":22430, "ctx":"Checkpointer","msg":"WiredTiger message","attr":{"message":{"ts_sec":1738421414,"ts_usec":157057,"thread":"103:0xf798af40ebc0","session_name":"WT_SESSION.checkpoint","category":"WT_VERB_CHECKPOINT_PROGRESS","category_id":6,"verbose_level":"DEBUG_1","verbose_level_id":1,"msg":"saving checkpoint snapshot min: 4, snapshot max: 4 snapshot count: 0, oldest timestamp: (0, 0) , meta checkpoint timestamp: (0, 0) base write gen: 7"}}}
MongoDB is now available.
Unfortunately, I don't have a client to connect to the new MongoDB database, and my favourite SQL tool DBeaver
supports MongoDB only in professional license. But when I use the address and the port of it in browser (http://<mongodb server>:27017
), I get
It looks like you are trying to access MongoDB over HTTP on the native driver port.
Ok, let's try another way - use the MongoDB shell inside the container:
# mongosh -u root
Enter password: *************
Current Mongosh Log ID: 67a0b5983b8836813aa00aa0
Connecting to: mongodb://<credentials>@127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+2.3.8
Using MongoDB: 7.0.16
Using Mongosh: 2.3.8
For mongosh info see: https://www.mongodb.com/docs/mongodb-shell/
To help improve our products, anonymous usage data is collected and sent to MongoDB periodically (https://www.mongodb.com/legal/privacy-policy).
You can opt-out by running the disableTelemetry() command.
------
The server generated these startup warnings when booting
2025-02-03T09:47:59.311+00:00: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine. See http://dochub.mongodb.org/core/prodnotes-filesystem
2025-02-03T09:48:00.239+00:00: vm.max_map_count is too low
------
test>
As we can see, we're inside the MongoDB. In fact, there are some warnings, but I assume they are relevant only in production environments.
We can do some further tests, like switching the database:
test> use sample_mflix
switched to db sample_mflix
And we can also insert some data:
db.movies.insertOne(
{
title: "The Favourite",
genres: [ "Drama", "History" ],
runtime: 121,
rated: "R",
year: 2018,
directors: [ "Yorgos Lanthimos" ],
cast: [ "Olivia Colman", "Emma Stone", "Rachel Weisz" ],
type: "movie"
}
)
This is the log we get:
{
acknowledged: true,
insertedId: ObjectId('67a0b8421631f5b127a00aa1')
}
We can also query the data:
db.movies.find( { title: "The Favourite" } )
[
{
_id: ObjectId('67a0b8421631f5b127a00aa1'),
title: 'The Favourite',
genres: [ 'Drama', 'History' ],
runtime: 121,
rated: 'R',
year: 2018,
directors: [ 'Yorgos Lanthimos' ],
cast: [ 'Olivia Colman', 'Emma Stone', 'Rachel Weisz' ],
type: 'movie'
}
]
If you want to learn more about MongoDB Shell, see here.