Skip to content

Instantly share code, notes, and snippets.

@wcxaaa
Last active March 23, 2020 14:01
Show Gist options
  • Save wcxaaa/219af2ab387f5c04bbcade9f7592477e to your computer and use it in GitHub Desktop.
Save wcxaaa/219af2ab387f5c04bbcade9f7592477e to your computer and use it in GitHub Desktop.
Dockerized mongoDB initialization

First create a mongod config file. e.g.

# mongod.conf
# Where and how to store data.
storage:
  dbPath: /data/db
  directoryPerDB: true
  journal:
    enabled: true
  engine: wiredTiger
  
# network interfaces
net:
  port: 27017
  bindIp: 127.0.0.1
  
# how the process runs
processManagement:
  timeZoneInfo: /usr/share/zoneinfo

security:
  authorization: disabled
  

Then run mongo.

$ docker run --name mongo-c1 -d -v /workspace/serverCenter/mongo/mongod.conf:/etc/mongod.conf -v /workspace/docking:/workspace/docking mongo -f /etc/mongod.conf
$ docker exec -it mongo-c1 mongo

In mongoshell, create an admin.

> use admin
> db.createUser({ user: 'root', pwd: 'some-initial-password', roles: [ { role: "root", db: "admin" } ] });
> exit

Then switch security.authorization to enabled in your conf file.

After that, you may restart your mongo container.

$ docker restart mongo-c1
# Check container IP
$ docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' mongo-c1

In future, to login to mongo, type:

$ docker exec -it mongo-c1 mongo -u root -p 'some-initial-password' --authenticationDatabase admin
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment