Martin
Martin

Reputation: 1267

How to add a user to a mongoDB database running in a docker container?

I want to add a custom user to a MongoDB database running on docker.

I started my image using the following command:

docker run -p 27017-27019:27017-27019 
--name mongo 
-e MONGO_INITDB_ROOT_USERNAME=mongoadmin 
-e MONGO_INITDB_ROOT_PASSWORD=secret 
-e MONGO_INITDB_DATABASE=interviewTest 
-d mongo

and after all, I am trying to run the bash command to ,,talk'' with my container like:

docker exec -it mongo bash

after all I am using command in terminal:

mongo

and I am receiving information in log:

MongoDB shell version v4.2.0
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("57a90f02-6ba4-4ef3-8bba-8a5f1b424574") }
MongoDB server version: 4.2.0

Seemingly everything is ok, I can create database with the command:

use test

but when I am trying to list database with the command:

show dbs

I am not receiving any result in the command line. The command is accepted and I am receiving empty line with a blinking cursor.

Moreover, when I am trying to create a database on my own like test with command

use test

seemingly it is created without any problem but after all when I want to try to create a user with a script:

db.createUser(
{
    user: "myUser",
    pwd: "myPassword",
    roles: [ { role: "readWrite", db: "interviewTest" }, "readWriteAnyDatabase" ]
}
);

I am receiving an error:

QUERY [js] uncaught exception: Error: couldn't add user: command createUser requires authentication :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
DB.prototype.createUser@src/mongo/shell/db.js:1370:11

Seemingly with above command docker run I should have a database and list it without any problem. I have a Mongo Explorer and after use test, there is no new database created.

I will be grateful for a solution which will give a possibility to create a user in my database and list DBs.

Upvotes: 0

Views: 2051

Answers (1)

matthPen
matthPen

Reputation: 4363

In fact you currently create the admin user (and implicitely activate authentication), but never use it to connect to your db.

Providing username and password while connecting will grant you access as admin, then you will be able to create other users :

mongo --username mongoadmin --password --host localhost:27017 --authenticationDatabase admin

Upvotes: 1

Related Questions