Skip to content

Instantly share code, notes, and snippets.

@DoZator
Last active July 3, 2023 09:31
Show Gist options
  • Save DoZator/25015d339f91286aa822ba43637ef942 to your computer and use it in GitHub Desktop.
Save DoZator/25015d339f91286aa822ba43637ef942 to your computer and use it in GitHub Desktop.
Enable Mongodb auth with Docker
  • Run mongodb without auth
  docker run --name mongo_db --cpus="1" -m 2G -e MONGODB_EXTRA_FLAGS='--wiredTigerCacheSizeGB=1' --restart always -v /home/$USER/.mongodata:/data/db -d mongo:3.6
  • Connect to mongodb without auth and create root user
  use admin
  db.createUser({ user: "root", pwd: "root_password", roles: [ "root" ] });
  • Create other user (for app database)
  use my_db_name
  db.createUser({ user: "my_db_user", pwd: "my_db_password", roles:[ { role: "readWrite", db: "my_db_name" } ] });
  • Create read only user (for app database)
  use my_db_name
  db.createUser({ user: "my_db_readonly_user", pwd: "my_db_readonly_password", roles:[ { role: "read", db: "my_db_name" } ] });
  • Run mongodb with auth (enable auth in mongodb with --auth flag)
  docker run --name mongo_db --cpus="1" -m 2G -e MONGODB_EXTRA_FLAGS='--wiredTigerCacheSizeGB=1' --restart always -v /home/$USER/.mongodata:/data/db -d mongo:3.6 --auth
  • Connect to mongodb with auth (root admin user)
  docker exec -it mongo_db mongo -u root -p root_password
  • Connect to mongodb with auth (database user)
  docker exec -it mongo_db mongo -u my_db_user -p my_db_password --authenticationDatabase my_db_name
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment