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"
Related
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 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.
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.
My mongo shell is giving me this error when I am using show dbs command.
not authorized on admin to execute command
I have tried to create a user using
db.createUser(
{
user: "siteUserAdmin",
pwd: "password",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
as on https://docs.mongodb.com/v2.6/tutorial/add-user-administrator/
But it still gives me the same error:
Could not add user: not authorized on admin to execute command.
I am using Ubuntu 16.04 and mongoDB version is 3.4.9
I think you can use the role as root for Ubuntu. Try the below query.
use admin
db.createUser(
{
user: "admin",
pwd: "password",
roles: [ { role: "root", db: "admin" } ]
}
);
exit;
You can give read write permission to user as well
use admin
db.grantRolesToUser("admin",["readWrite"])
EDIT
Since the above didn't work try to start the instance with auth as below
Stop the mongod instance
Start the instance with $ mongod --auth
Now start mongo shell and create user
use admin
db.createUser(
{
user: "admin",
pwd: "password",
roles: [ { role: "root", db: "admin" } ]
}
);
exit;
Now give permission
db.auth("admin", "password")
db.grantRolesToUser("password", [ { role: "readWrite", db: "admin" } ])
Now check show users
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