carl saptarshi
carl saptarshi

Reputation: 355

Docker - Creating First User with MongoDB

I am new to docker, and am trying to set up my first mongo db user on my docker container. I followed this get mongo for docker tutorial to get started, which provided this .yml file:

# Use root/example as user/password credentials

version: '3.1'
services:

  mongo:
    image: mongo
    restart: always
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: example
  mongo-express:
    image: mongo-express
    restart: always
    ports:
      - 8081:8081
    environment:
      ME_CONFIG_MONGODB_ADMINUSERNAME: root
      ME_CONFIG_MONGODB_ADMINPASSWORD: example

I then used docker-compose up to create my container instance. Once this was done, I ssh'ed into the container and tried to do a simple show dbs query. Whenever I run this, or any other command, I get the following authorisation message:

> use admin
switched to admin
> show dbs
2018-06-09T17:20:48.644+0000 E QUERY    [thread1] Error: listDatabases failed:{
    "ok" : 0,
    "errmsg" : "not authorized on admin to execute command { 
         listDatabases: 1.0, $db: \"admin\" }",
    "code" : 13,
    "codeName" : "Unauthorized"
}

I read that when you use environment variables like MONGO_INITDB_ROOT_USERNAME and MONGO_INITDB_ROOT_PASSWORD, that you didn't have to use --auth as this covers me, so I could do things like creating users? https://stackoverflow.com/a/42973849/4819186

Would someone be able to point me in the right direction on how to set the user up correctly? Thanks.

Upvotes: 0

Views: 1368

Answers (1)

Gustavo Topete
Gustavo Topete

Reputation: 1296

you need to authenticate yourself when connecting to the mongod (mongo server). You need to use something like:

mongo --host my_host -u user -p password --authenticationDatabase admin

with this you're basically authenticating yorurself against admin database, now you should have the right privileges

Upvotes: 1

Related Questions