Home / Configs / Containers / docker-compose for MongoDB

docker-compose for MongoDB: example file and generator

Run a local MongoDB database with a password that keeps its data.

For Docker Desktop (Windows, macOS) or Docker Engine with the Compose plugin (Linux). Use "docker compose", not "docker-compose".

This docker-compose file starts a MongoDB database on your computer with one command and keeps your data between restarts. The port is open only on your own computer. Choose your version, user, password and port below, then run docker compose up -d.

Create your config file

Type your own values. The file below updates as you type, and nothing you type leaves your browser.

Click Generate for a strong one
Change if 27017 is taken

docker-compose.yml
services:
  mongo:
    image: mongo:8
    restart: unless-stopped
    environment:
      MONGO_INITDB_ROOT_USERNAME: admin
      MONGO_INITDB_ROOT_PASSWORD: change-me
    ports:
      - "127.0.0.1:27017:27017"
    volumes:
      - mongo_data:/data/db

volumes:
  mongo_data:

How this setup works

Diagram: docker compose up, then MongoDB container, then mongo_data volume
docker compose up (one command) → MongoDB container (your port) → mongo_data volume (data is kept)

Step-by-step setup

  1. Install Docker Desktop (Windows, macOS) or Docker Engine (Linux).
  2. Save the config above as docker-compose.yml in an empty folder.
  3. Change the password.
  4. Run docker compose up -d.
  5. Connect: mongosh "mongodb://admin:PASSWORD@localhost:27017", using your password.

What the important lines mean

Common errors and how to fix them

Authentication failed
The admin user is created only when the volume is empty. If you changed the password later, run docker compose down -v and start again. This deletes the data.
port is already allocated
Something else already uses port 27017. Pick another port above, such as 27018.
command requires authentication
You connected without a user. Add the user and password to the connection string.

Frequently asked questions

How do I connect to MongoDB running in Docker?
Use mongosh with a connection string such as mongodb://admin:PASSWORD@localhost:27017, replacing the user, password and port with your own.
Will I lose my data when I stop the container?
No, as long as the volume is in the file. Data is lost only if you run docker compose down -v, which deletes the volume.
Why is the port bound to 127.0.0.1?
So that only programs on your own computer can reach the database. Remove 127.0.0.1: from the ports line only if you really need access from other machines, and then use a strong password and a firewall.

Written for: Docker Compose v2, official mongo image · Updated 2026-10-11

Free tools that help

Fix a problem with this setup

More container configs

See all 41 config generators