Run MongoDB in a Docker container on Docker for Windows
Running MongoDB in a Docker container is the fastest way to get a local database for development without installing MongoDB directly on your machine. On Docker for Windows (or Docker Desktop on any platform) it takes two commands: create a named volume so your data survives container restarts, then start the official mongo image with that volume mounted and the default port published.
Create a volume to persist the database files:
1
docker volume create --name=mongodata
Then run a MongoDB instance:
1
docker run -d --name mongo -p 27017:27017 -v mongodata:/data/db mongo
What each flag does
-druns the container detached, in the background.--name mongogives the container a friendly name, so you candocker stop mongoanddocker start mongolater.-p 27017:27017publishes MongoDB’s default port to your host, so tools and apps can connect onlocalhost:27017.-v mongodata:/data/dbmounts the named volume at MongoDB’s data directory, so your data persists even if you remove and recreate the container.
Connecting to it
Open a shell inside the container with the modern mongosh client:
1
docker exec -it mongo mongosh
Applications connect with the standard connection string mongodb://localhost:27017.
Enabling authentication
The command above runs without authentication, which is fine for a throwaway local database but should never be exposed. To require credentials, set the root username and password when the container is first created (they are only applied to an empty data directory):
1
2
3
4
docker run -d --name mongo -p 27017:27017 -v mongodata:/data/db \
-e MONGO_INITDB_ROOT_USERNAME=admin \
-e MONGO_INITDB_ROOT_PASSWORD=secret \
mongo
Pin a version
Plain mongo pulls the latest image, which can change under you and occasionally introduces breaking upgrades to the data files. For reproducible environments, pin a major version tag such as mongo:7.
Stopping and cleaning up
1
2
docker stop mongo
docker rm mongo # the mongodata volume (and your data) remains
Because the data lives in the mongodata volume rather than inside the container, you can remove and recreate the container freely without losing your database.