I am trying to create a docker-compose file for MongoDB after checking out multiple examples on the web and this is my configuration. However after executing docker-compose up command, when trying to login using any of the below credentials in Compass at localhost:37017, I am getting the error:
UserNotFound: Could not file user "dbAdmin" for db "admin"
Folder structure
mongo [directory]
docker-entrypoint-initdb.d [directory]
mongo-init.js
mongo-volume [directory]
docker-compose.yml
docker-compose.yml content:
version: '3'
services:
mongoDB:
image: 'mongo:latest'
container_name: 'app-mongo'
environment:
- MONGO_INITDB_ROOT_USERNAME=dbAdmin
- MONGO_INITDB_ROOT_PASSWORD=TtUBhMjOIfeV
- MONGO_INITDB_DATABASE=admin
volumes:
- ./docker-entrypoint-initdb.d/mongo-init.js:/docker-entrypoint-initdb.d/mongo-init.js:ro
- ./mongo-volume:/data/db
ports:
- '37017-37019:27017-27019'
mongo-init.js content
let admin = db.getSiblingDB("admin");
admin.createUser({
user : "appAdmin",
password: "TtUBhMjOIfeV",
db: "admin",
roles: [
{
role: "clusterAdmin",
db: "admin"
},
{
role: "userAdminAnyDatabase",
db: "admin"
}
]
});
admin.createCollection("users");
let adppDBName = db.getSiblingDB("appDBName");
appDBName.createUser({
user: "appOwner",
password: "EtMxw6ZY9jiG",
db: "admin",
roles: [
{
role: "readWrite",
db: "appDBName"
}
]
});
appDBName.createCollection("users");
You created a user named appAdmin but are apparently trying to use a user named dbAdmin.
Related
I always get this error trying to connect to the Mongodb
MongoDB Response
server selection error: server selection timeout, current topology: { Type: ReplicaSetN
oPrimary, Servers: [{ Addr: mongodb:27017, Type: Unknown, Last error: connection() error occured during connection handshake: dial tcp: lookup mongodb: no such host }, ] }
MongoDB Log
mongodb | 2022-03-08T06:40:26.387+0000 I NETWORK [conn14]
received client metadata from 172.25.0.1:39218 conn14: { driver: {
name: "mongo-go-driver", version: "v1.8.3" }, os: { type: "windows",
architecture: "amd64" }, platform: "go1.17.5" }
Here is how I set up
docker-compoes.yml
mongodb:
container_name: mongodb
build: ./mongo
ports:
- 27017:27017
environment:
- MONGODB_USER=debezium
- MONGODB_PASSWORD=dbz
networks:
- pg-es-synch_default
Dockerfile
FROM mongo:3.6
CMD ["mongod", "--replSet", "rs0", "--auth"]
Command
>> mongo localhost:27017/ecommerce_connect
rs.initiate({
_id: "rs0",
members: [ { _id: 0, host: "mongodb:27017" } ]
});
>> mongo localhost:27017/admin
db.createUser({ user: 'admin', pwd: 'admin', roles: [ { role: "userAdminAnyDatabase", db: "admin" } ] });
>> mongo -u admin -p admin localhost:27017/admin
db.createUser({
user:
'debezium',
pwd: 'dbz',
roles: [
{ role: "readWrite", db: "ecommerce_connect" },
{ role: "readWrite", db: "local" },
{ role: "root", db: "admin" },
{ role: "readWrite", db: "config" },
]
});
When I login by user debezium outside Docker in the localhost I always got the error mentioned above.
But if I do this in CLI of Docker, It works
>> mongo -u debezium -p dbz --authenticationDatabase admin localhost:27017/ecommerce_connect
use ecommerce_connect;
db.product_info.insert([
{ _id : NumberLong("128"), name : 'scooter', description: 'Small 2-wheel scooter', weight : 3.14, quantity : NumberInt("3") }
]);
I connect to mongoDB by this URL:
"mongodb://debezium:dbz#localhost:27017"
I have a ReplicaSet in which I created a user like this:
db.createUser({
user: "myuser",
pwd:"mypassword",
roles: [
{
role: "userAdminAnyDatabase",
db: "admin"
},
{
role: "dbAdminAnyDatabase",
db: "admin"
},
{
role: "readWriteAnyDatabase",
db:"admin"
},
{
role: "clusterAdmin",
db: "admin"
}
]});
When I activate then authorization in my config file like this:
security:
authorization: enabled
keyFile: /my/file.key
I restart replicaset nodes and try to connect using :
mongo mongodb://myuser:mypassword#host1:port,host2:port,host3:port/?replicaSet=myReplicaName&authSource=myDbName
I get Error: can't connect to new replica set master [ip:port], err: AuthenticationFailed: Authentication failed.
Any idea what could be missing?
I am using following docker-compose file
version: '3.7'
services:
db_container:
image: mongo:latest
restart: always
environment:
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: password
MONGO_INITDB_DATABASE: root-db
ports:
- 27017:27017
volumes:
- ./database/initdb.js:/docker-entrypoint-initdb.d/initdb.js:ro
- ./data:/data/db
Here is my initdb.js file
db.createUser(
{
user: "api-test",
pwd: "api-test",
roles: [
{
role: "readWrite",
db: "api-test"
}
]
}
);
I can see only 3 databases and unable to connect to api-test DB
Please help me if something is missing
Able to solve the issue with the help of the following article
Docker-Compose mongoDB Prod, Dev, Test Environment
The file structure should be
Project
├── docker-compose.yml (File)
├── docker-entrypoint-initdb.d (Directory)
│ ├── mongo-init.js (File)
docker-compose.yml file
version: '3.7'
services:
mongo:
container_name: container-mongodb
image: mongo:latest
restart: always
ports:
- 27017:27017
environment:
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: password
MONGO_INITDB_DATABASE: root-db
volumes:
- ./docker-entrypoint-initdb.d/mongo-init.js:/docker-entrypoint-initdb.d/mongo-init.js:ro
mongo-init.js file
print('Start #################################################################');
db = db.getSiblingDB('api_prod_db');
db.createUser(
{
user: 'api_user',
pwd: 'api1234',
roles: [{ role: 'readWrite', db: 'api_prod_db' }],
},
);
db.createCollection('users');
db = db.getSiblingDB('api_dev_db');
db.createUser(
{
user: 'api_user',
pwd: 'api1234',
roles: [{ role: 'readWrite', db: 'api_dev_db' }],
},
);
db.createCollection('users');
db = db.getSiblingDB('api_test_db');
db.createUser(
{
user: 'api_user',
pwd: 'api1234',
roles: [{ role: 'readWrite', db: 'api_test_db' }],
},
);
db.createCollection('users');
print('END #################################################################');
Although my setup was correct, removed volumes, modified the db, etc, none of these worked for me.
The only way was to change the name of the mongodb container inside the docker-compose, instead of mongo I wrote mongodb and it worked.
everyone,
I'm having a hard time setting up a MongoDB container to have root password and creating a new user with less privileges (that will be my application user) automatically.
Ideally I should have only some scripts and a docker-compose configuration.
I tried adding the MONGO_INITDB_ROOT_USERNAME and MONGO_INITDB_ROOT_PASSWORD but they don't seem to work. They do something, because when I start the container like that, I can't just connect to the mongo shell and run all the commands (and passing username and password will throw unauthorized errors).
Then I thought about adding a script at /docker-entrypoint-initdb.d/ but they dont seem to run. They don't show on console. Besides, i just put a javascript like this and I am not sure whether they will work:
var db = connect("mongodb://localhost/admin");
db.createRole(
{
role: "somerole",
privileges: [
{
actions: [ "find", "update", "insert" ],
resource: { db: "mydb", collection: "" } <--- does it means all colections od database mydb?!?!
}
],
roles: [ ]
}
)
db.createUser(
{
user: "admin",
pwd: "adminpass",
roles: [ { role: "userAdminAnyDatabase", db: "mydb" } ]
}
)
db.createUser(
{
user: "system",
pwd: "systempass",
roles: [ { role: "somerole", db: "mydb" } ]
}
)
I would also want to create collections and insert documents. How do we do that? Shouldn't it be with entrypoints!?
MongoDb Documentation: Security Reference
Partial response 1
Partial response 2
1) Create the following structure of files:
2) Content of docker-compose.yml
version: "3"
services:
mongodb:
image: "mongo:4.1.1-xenial"
restart: "unless-stopped"
env_file:
- ".env"
ports:
- "27017:27017"
volumes:
- "./database/data:/data/db" # Database files
- "./database/fixtures:/docker-entrypoint-initdb.d" # To create Db at start
3) Content of default.js
/* Create a New user with "only READ" role */
db = db.getSiblingDB('admin');
db.createUser(
{
"user": "John",
"pwd": "MyPassword",
"roles": [
{ "role": "read", "db": "data" }
]
})
/* Misc - Other Data */
db = db.getSiblingDB('data');
db.data.save([
{
"name": "Frank",
"email": "email1#gmail.com",
},
{
"name": "Peter",
"email": "email2#gmail.com",
}
]);
4) Content of .env
MONGO_INITDB_ROOT_USERNAME=Robert
MONGO_INITDB_ROOT_PASSWORD=GoodPassword
5) Go to your terminal and at the level of the docker-compose.yml file, execute:sudo docker-compose up -d
6) Get the container's name:
Execute: sudo docker ps a
7) Go inside the container:
Execute: sudo docker exec -it <CONTAINER NAME> bash
8) Inside the container:
Execute: mongo --host localhost -u Robert -p GoodPassword --authenticationDatabase admin
NOTE: Take into account that we are specifying the "authentication database"
9) Select database:
Execute: use admin
10) Show users (You must find two users Robert and John):
Execute: show users
As you can see inside "data" directory are stored the files of the database.
And using the default.js file you can create collections frm the start.
IMPORTANT NOTE: If you make some changes and those are not reflected to the database, then you need to DELETE the content of "data" and run again: docker-compose up -d
We can say that, if "data" directory is not empty, then the "default.js" file will not be taked into account.
I changed a bit your configuration and it runs correctly:
docker-compose.yml:
version: '3.1'
services:
mongo:
image: mongo
restart: always
volumes:
- ./init.js:/docker-entrypoint-initdb.d/init.js
environment:
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: example
MONGO_INITDB_DATABASE: mydb
here I specify the database to be created initially and I also mount the init script.
init.js:
var db = connect("mongodb://localhost/mydb");
db.createRole(
{
role: "somerole",
privileges: [
{
actions: [ "find", "update", "insert" ],
resource: { db: "mydb", collection: "" }
}
],
roles: [ ]
}
)
db.createUser(
{
user: "admin",
pwd: "adminpass",
roles: [ { role: "somerole", db: "mydb" } ]
}
)
db.createUser(
{
user: "system",
pwd: "systempass",
roles: [ { role: "somerole", db: "mydb" } ]
}
)
The important part here is the first line, otherwise you create a role in the admin database while you look for it in mydb database.
With this setup I can start the database and connect to it.
I have create a user in Mongo 3.0.4 and enable authentication, I can login in Mac but not in Ubuntu 14.04
This is how I followed process to enable authentication
use admin
db.createUser(
{
user: "mongoUser",
pwd: "User123##!",
roles: [
{ role: "read", db: "trackuser" },
{ role: "readWrite", db: "trackuser" },
{ role: "dbAdmin", db: "trackuser" },
{ role: "dbOwner", db: "trackuser" }
]
}
)
auth=true in /etc/mongod.conf
$ mongo -u mongoUser -p User123##! --authenticationDatabase trackuser
MongoDB shell version: 3.0.4
connecting to: 127.0.0.1:27017/test
2015-07-16T14:44:54.741+0200 E QUERY Error: 18 Authentication failed.
at DB._authOrThrow (src/mongo/shell/db.js:1266:32)
at (auth):6:8
at (auth):7:2 at src/mongo/shell/db.js:1266
exception: login failed
What to do in this case?? Same version Working in Mac but not in Ubuntu??
You can try adding new parameter for DB name like this
-d trackuser
right now i guess you are using
--authenticationDatabase trackuser