Skip to content
Runbook

Install MongoDB on Docker

Document-oriented NoSQL database (BSON), designed for horizontal scalability and flexible schemas.

Databasenosqldocumentdatabasebson

Installation

Container (with volume) · Docker
docker run -d --name mongodb -p 127.0.0.1:27017:27017 -v mongodb_data:/data/db mongo:8

The named volume mongodb_data ensures data persistence across restarts. As long as authentication is not enabled, publish the port on the loopback interface only (127.0.0.1) so MongoDB is not exposed on all interfaces.

With authentication · Docker
docker run -d --name mongodb -p 27017:27017 -v mongodb_data:/data/db -e MONGO_INITDB_ROOT_USERNAME=admin -e MONGO_INITDB_ROOT_PASSWORD=secret mongo:8

Choose a strong password. Passing MONGO_INITDB_ROOT_PASSWORD in plaintext exposes it via docker inspect, docker ps and the shell history: prefer --env-file, Docker secrets, or the MONGO_INITDB_ROOT_PASSWORD_FILE variant that reads the password from a mounted file.

Verify the installation

Verify
docker exec mongodb mongosh --eval "db.runCommand({ ping: 1 })"

Service

Start
docker start mongodb
Stop
docker stop mongodb
Status
docker ps --filter name=mongodb
Restart
docker restart mongodb

Important files

TypePathDescription
data/data/dbData directory inside the container (to be mounted on a volume).
config/etc/mongod.conf.origDefault configuration copied into the image, but NOT read at startup: mongod is launched via CMD ['mongod'] without --config. To apply a config, mount your own file AND override the command (command: ['mongod','--config','/etc/mongod.conf']).

Default ports

27017

Command-line tools

  • docker exec -it mongodb mongoshOpens the mongosh shell inside the container.

Uninstall

Remove (container + data)
docker rm -f mongodb
docker volume rm mongodb_data

Removing the volume permanently erases the data.

Good to know

  • Without a volume, data is lost when the container is removed.
  • The official image is mongo (Docker Hub); pin a major version (mongo:8) in production.

MongoDB with Docker

The official mongo image starts a ready-to-use server. Mount a named volume on /data/db to keep your data. Expose port 27017 to access it from the host.

For a deployment, define a root user via MONGO_INITDB_ROOT_USERNAME / MONGO_INITDB_ROOT_PASSWORD and pin a specific image version.