How to set-up Mongo replica set on Kubernetes? - mongodb

I'm trying set-up a three node Mongo replica set on Kubernetes. My thoughts is start three pods, with Mongo in each one, when the pod starts, it automatically sets up the replica set, so I need to modify the Mongo image Dockerfile to execute some command in Mongo shell.
But I am stuck at executing the command rs.initiate(). If I just use the command rs.initiate() without parameters it works, but when adding parameters then it occurs error like
rs.initiate({ "_id": "rs0", "members" : [ { "_id" : 0, "host" : "172.18.248.87:27017" } ]})
But when executing the pod and using the same command with parameters, it works. The same situation with the command rs.add() . How to resolve this?
Plus: in my Dockerfile I use mongo admin --port 27017 --eval "rs.initiate()" to execute the command .

You should check hosts file (hostname) in pod and add :
ip_address mongoslave
ip_address mongomaster
For example :
172.18.248.87 mongomaster
Then you add parametters:
rs.initiate()
rsconf = {
_id: "rs0",
members: [
{
_id: 0,
host: "mongomaster:27017"
}
]
}
rs.reconfig(rsconf, {force: true})

Related

mongo : not authorizeed on admin to execute on admin to execute command

I am new to Mongod, and have to get up a cluster. The db is started with --replSet=Data and I have created the cluster with rs.Initiate beforehand. But this question is about user administration.
This replica set was set up with this command:
rs.initiate({ _id : "Data",members: [
{ _id: 0, host: "srv1:27017" },
{ _id: 1, host: "srv2:27017" },
{ _id: 2, host: "srv3:27017" , arbiterOnly: true }
})
And the server was started with $ /usr/bin/mongod -f /etc/mongod.conf --replSet=rs0
Note that I have not yet configured the other nodes/added these into the cluster as far as I am aware, but I did distribute the keyFile: /etc/mongod/keyfile to each server.
An rs.status says it's not running.
> rs.Status();
{
"ok : 0"
"errmsg" : no replset config has been received",
"code" : 94,
"codename" : "NotYetInitialized"
}
I have run into some nib problems.
I created a user before called mgdb with the command :
# mongo admin -port 27017
> db.createUser ( {
user : 'mgdb', pwd: 'password', roles: [ { roles: root, db: admin } ]
})
This returned ok.
Next I tried with,
$ mongo --authenticationDatabase admin --username "mgdb" --password "password"
but got an error
E QUERY [js] Error authentication failed.
Next I tried to see the user list,
> show users;
not authorizeed on admin to execute on admin to execute command { UserInfo: 1.0}, lsid: { id: UID"xxxxxxxx") }. $db: "admin" } DB.prototy[e.getUsers#.....
So, I am bit lost. I used mysql a few years ago, but have not used it since. My dB experience is very little.
Although I can connect as the admin user, the admin user does not seem to have rights to do basic "show users;"
Where can I look in the dB to find out what went wrong?
Environment: RHEL 7.6 SELinux Enforcing, MOngdodB 4.2.9
In MongoDB you can create users per database. Usually users are create in database admin (I wouldn't know any reason to create them somewhere else):
use admin
db.createUser(...
or
db.getSiblingDB("admin").createUser(...
When you connect to Mongo then you need to specify the authentication database, i.e. the database where user was created:
mongo --usermame=mgdb --password 'password' --authenticationDatabase admin
See Authentication failure while trying to save to mongodb
In order to deploy a sharded cluster have a look at Deploy a Sharded Cluster or Deploy a Replica Set tutorial.

MongoDB add replica-set to external server by ip

I have created 3 Digitalocean droplet. By default, I choose Ubuntu 18.06 and MongoDB 4.
Here I have 3 droplets by default MongoDB config and all are up. I have access to "mongo" shell for all of them.
Now I want to run a replica-set setting by this code:
rs.initiate(
{_id : "rs0",
members: [
{ _id: 0, host: "20.30.40.50:27017" },
{ _id: 1, host: "20.30.40.51:27017" },
{ _id: 2, host: "20.30.40.52:27017" }
]
})
In this config, I just told MongoDB that rune the replica set and it retrieves me the error
no replies config has been received
I did not add any bindIp yet also when I added bindIp, I could not start MongoDB again. I put in mongo.conf like this:
bindIp: 127.0.0.1,20.30.40.51,20.30.40.52
Also, There is a private network between these 3 droplets by IP example: 10.10.1.1 Can I take advantage of this private IP to make it easier and safer?

Docker MongoDB Cannot sign in as root

I'm trying to set up mongo using docker but I don't know the correct way to log in to mongo. It doesn't seem to have created the default root user as I have specified:
version: '3'
services:
location-mongo-db:
container_name: location-mongo-db
image: mongo
ports:
- "27017:27017"
restart: always
environment:
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: example
networks:
default:
external:
name: environment_location-mongo
I run
docker-compose -f docker-compose/db.yml -p location-mongo-db up -d --build
I then do
docker exec -it location-mongo-db sh
to get in to the shell and run # mongo from inside the container. I get the following:
# mongo
MongoDB shell version v4.0.0
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 4.0.0
> show dbs
2018-06-28T15:45:36.337+0000 E QUERY [js] Error: listDatabases failed:{
"ok" : 0,
"errmsg" : "command listDatabases requires authentication",
"code" : 13,
"codeName" : "Unauthorized"
} :
_getErrorWithCode#src/mongo/shell/utils.js:25:13
Mongo.prototype.getDBs#src/mongo/shell/mongo.js:65:1
shellHelper.show#src/mongo/shell/utils.js:865:19
shellHelper#src/mongo/shell/utils.js:755:15
#(shellhelp2):1:1
I don't know what the issue is. Here is my output from checking for the list of users:
> db.runCommand({connectionStatus : 1})
{
"authInfo" : {
"authenticatedUsers" : [ ],
"authenticatedUserRoles" : [ ]
},
"ok" : 1
}
What is missing? I've tried signing in a few different ways with -u root and -p etc but nothing so far works
When you start mongo client without params on mongo command, you connect yourself as unauthenticated user, with very limited privileges.
The right command to connect from your docker tty (and from your host terminal since you expose mongodb port) with your root user credentials is :
mongo -u root -p example --authenticationDatabase admin
To fully disable connection without authetication, you need to start mongod process with the --auth option.
EDIT : According to the doc, it seems that with the two env variables MONGO_INITDB_ROOT_USERNAME and MONGO_INITDB_ROOT_PASSWORD set, mongod in docker container must start with --auth option automatically... but this behavior is not working for me.

MongoDB replica set configuration through js file

I have configured a replica set for MongoDB manually.
Once I have launched the daemons on 3 nodes and after they are up and running, from the node which I have identified as "Primary" I run the following command:
mongo
This will drop me into the mongo shell
use admin
Create replica set config:
cfg = {
_id: 'csReplicaSet',
members: [
{ _id: 0, host: 'node1IpAddress:27017'},
{ _id: 1, host: 'node2IpAddress:27017'},
{ _id: 2, host: 'node3IpAddress:27017', arbiterOnly: true}
]
}
rs.initiate(cfg)
I want to know how can I do these steps in a JavaScript file that will be recognised by mongo. I want to automate these steps.
Passing your init script to the mongo shell
Programmatically, you're almost there. You could save your instructions to a JavaScript file and run this on the mongo command line. You should also capture & print the results of rs.initiate() in case there is an error:
eg. contents of initreplica.js:
var cfg = { _id: 'csReplicaSet',
members: [
{ _id: 0, host: 'node1IpAddress:27017'},
{ _id: 1, host: 'node2IpAddress:27017'},
{ _id: 2, host: 'node3IpAddress:27017', arbiterOnly: true}
]
};
var error = rs.initiate(cfg);
printjson(error);
Run this from the command line with:
mongo node1IpAddress:27017/admin initreplica.js
Note that this assumes your three mongod nodes have been started on the same IP addresses including --replSet csReplicaSet parameter. You also only need to do this init sequence once unless you are rebuilding the replica set from scratch (and there is no existing replica set config).
I would also recommend reading the section of the manual on Writing Scripts for the mongo shell. It includes some helpful hints such as how to open new connections to other MongoDB servers as well as the JavaScript equivalents of some shell helpers like use <db>.
Automating a production deployment
If you're looking for ways to automate building a production MongoDB cluster, you should look into recipes for configuration management tools like Chef or Puppet. There is also an Automation feature coming soon as part of MMS (MongoDB Management Service); the Automation feature is currently in beta testing.
I Just run it this way
mongo --port 27018 init_replica.set.js
and this is the script for init from the
config = { _id: "m101", members:[
{ _id : 0, host : "MYHOST:27017" ,priority : 0, slaveDelay : 5 },
{ _id : 1, host : "MYHOST:27018"},
{ _id : 2, host : "MYHOST:27019"} ]
};
rs.initiate(config);
rs.status();

How to convert a MongoDB replica set to a stand alone server

Consider, I have 4 replicate sets and the config is as follows:
{
"_id": "rs_0",
"version": 5,
"members" : [
{"_id": 1, "host": "127.0.0.1:27001"},
{"_id": 2, "host": "127.0.0.1:27002"},
{"_id": 3, "host": "127.0.0.1:27003"},
{"_id": 4, "host": "127.0.0.1:27004"}
]
}
I am able to connect to all sets using
mongo --port <port>
There are documents for getting information on Convert a Standalone to a Replica Set, but can anyone tell me how to convert back to standalone from replica set?
Remove all secondary hosts from replica set (rs.remove('host:port')), restart the mongo deamon without replSet parameter (editing /etc/mongo.conf) and the secondary hosts starts in standalone mode again.
The Primary host is tricky one, because you can't remove it from the replica set with rs.remove.
Once you have only the primary node in the replica set, you should exit mongo shell and stop mongo. Then you edit the /etc/mongo.conf and remove the replSet parameter and start mongo again.
Once you start mongo you are already in standalone mode, but the mongo shell will prompt a message like:
2015-07-31T12:02:51.112+0100 [initandlisten] ** WARNING: mongod started without --replSet yet 1 documents are present in local.system.replset
to remove the warning you can do 2 procedures:
1) Droping the local db and restarting mongo:
use local
db.dropDatabase();
/etc/init.d/mongod restart
2)Or if you don't want to be so radical, you can do:
use local
db.system.replset.find()
and it will prompt a message like:
{ "_id" : "replicaSetName", "version" : 1, "members" : [ { "_id" : 0, "host" : "hostprimary:mongoport" } ] }
then you will erase it using:
db.system.replset.remove({ "_id" : "replicaSetName", "version" : 1, "members" : [ { "_id" : 0, "host" : "hostprimary:mongoport" } ] })
and it will probably prompt:
WriteResult({ "nRemoved" : 1 })
Now, you can restart the mongo and the warning should be gone, and you will have your mongo in standalone mode without warnings
Just remove a host from replica set (rs.remove('host:port')), relaunch it without replSet parameter and it's standalone again.
On an Ubuntu Machine
Stop your mongo server
open /etc/mongod.conf
Comment the replication and replSetName line
#replication:
#replSetName: rs0
Start your mongo server and go to mongo shell
drop local database
use local
db.dropDatabase()
Restart mongo
The MongoDB Documentation suggests the following to perform maintenance on a replica set member, which brings the the replica set member into standalone mode for further operations. With little modification it can be made standalone:
If node in concern is the only node in a shard, drain the chunks to other shards as per MongoDB documentation here, or else the sharded database will break, i.e.
Make sure balancer is enabled by connecting to mongos and run sh.startBalancer(timeout, interval)
For the shard in concern, go to admin database and db.adminCommand( { removeShard: "mongodb0" } )
Check draining status by repeating above removeShard command, wait for draining to complete
If node in concern is primary, do rs.stepDown(300)
Stop the node by running db.shutdownServer()
Change the yaml config by:
commenting out replication.replSetName (--replSetName in command line)
commenting out sharding.clusterRole for shard or config server (--shardsvc and --configsvr in command line)
commenting out net.port, then change it to a different port (--port in command line)
Start the mongod instance
If change is permanent, go to other mongod instance and run rs.remove("host:port")
After this, the node in concern should be up and running in standalone mode.
Follow below steps :
Go to mongo shell on Secondary servers
Stop the secondary servers by using below command :
use admin
db.shutdownServer()
Go to Linux shell- on secondary servers and type below command :
sudo service mongod stop
Starting the MongoDB replication -
Go to Linux shell - on secondary servers and type below command :
sudo service mongod start
Starting the MongoDB replication -
Go to primary and type below commands to start the replication :
a] rs.initiate()
b] rs.add("Secondar -1:port no")
c] rs.add("Secondary-2:port no")
d] rs.add({ "_id" : 3, "host" : "Hidden_member:port no", "priority" : 0,
"hidden" : true })
e] rs.status()