1001Ferramentas
🍃Dev

docker-compose MongoDB Generator

Generates a ready-to-use docker-compose for MongoDB, with root user and password, port 27017 published and a persistent volume. You create the database after it starts.

YAML

A local MongoDB without memorizing YAML

You want Mongo running in five minutes to test an app, without installing anything on the host, and you can never remember the exact environment variable names the image expects. One typo in MONGO_INITDB_ROOT_USERNAME gives you a database with no authentication at all, and you find out when someone connects without a password. Fill in the image tag, the root user and the root password, and the service YAML comes out ready.

Here is the part that trips people up: MONGO_INITDB_ROOT_USERNAME and MONGO_INITDB_ROOT_PASSWORD are only read on the very first startup, while the data directory is still empty. If the mdata volume already exists, changing the password in the compose file does nothing. You have to run docker compose down -v. And the root user lives in the admin database, so the connection string needs mongodb://root:rootpass@localhost:27017/?authSource=admin

What you get is the core: service, image, root credentials, published port 27017 and a named volume. An initial database name, replica sets and scripts in docker-entrypoint-initdb.d are on you. A password containing a colon followed by a space, a hash sign or quotes will break the YAML, so wrap it in quotes or move it to a .env file. Publishing 27017:27017 also exposes the database on every interface. Everything is built in your browser.

Frequently asked questions

I changed the password in the compose file and Mongo still accepts the old one. Why?
The data volume was already initialized. The MONGO_INITDB_ROOT_* variables only apply when the data directory is empty. Run docker compose down -v to drop the volume, then bring it back up.
What connection string works with this compose file?
mongodb://user:password@localhost:27017/?authSource=admin. The authSource part is required because the root user is created in the admin database, not in your application database.
Can I use this in production?
Not as generated. The password sits in plain text in the file and the port is published on all interfaces. For production, use secrets or external environment variables and restrict the bind address.

Related Tools