For a proper mongodb replication, we are going to start 3 containers for this exercise.
docker run -dit --name mongorep1 --hostname mongorep1 mongo:6 --bind_ip_all --replSet myrepl
docker inspect mongorep1 | grep -w IPAddress"IPAddress": "172.17.0.2",
docker run -dit --name mongorep2 --hostname mongorep2 --add-host mongorep1:172.17.0.2 mongo:6 --bind_ip_all --replSet myrepl
docker run -dit --name mongorep3 --hostname mongorep3 --add-host mongorep1:172.17.0.2 mongo:6 --bind_ip_all --replSet myrepl
docker exec -it mongorep1 mongoshtest> rs.initiate()
myrepl [direct: secondary] test> rs.add("172.17.0.3")myrepl [direct: primary] test> rs.add("172.17.0.4")
myrepl [direct: primary] test> rs.status()
...
members: [
{
_id: 0,
name: 'mongorep1:27017',
health: 1,
state: 1,
stateStr: 'PRIMARY',
...
{
_id: 1,
name: '172.17.0.3:27017',
health: 1,
state: 2,
stateStr: 'SECONDARY',
...
{
_id: 2,
name: '172.17.0.4:27017',
health: 1,
state: 2,
stateStr: 'SECONDARY',
...
myrepl [direct: primary] test> db.printSecondaryReplicationInfo()
source: 172.17.0.3:27017
{
syncedTo: 'Mon Dec 19 2022 15:48:01 GMT+0000 (Coordinated Universal Time)',
replLag: '0 secs (0 hrs) behind the primary '
}
---
source: 172.17.0.4:27017
{
syncedTo: 'Mon Dec 19 2022 15:48:01 GMT+0000 (Coordinated Universal Time)',
replLag: '0 secs (0 hrs) behind the primary '
}
docker exec -it mongorep1 mongoshmyrepl [direct: primary] test> use mynewdbmyrepl [direct: primary] mynewdb> db.people.insertOne( { name: "John Rambo", occupation: "Soldier" } )exit
docker exec -it mongorep2 mongoshmyrepl [direct: secondary] test> show dbsmyrepl [direct: secondary] test> use mynewdbmyrepl [direct: secondary] test> db.people.find()
[
{_id: ObjectId("63a08880e1c97fba6959ec15"),name: 'John Rambo',occupation: 'Soldier'}]
If you encounter this error:
MongoServerError: not primary and secondaryOk=false - consider using db.getMongo().setReadPref() or readPreference in the connection string
myrepl [direct: secondary] test> db.getMongo().setReadPref("secondary")
Do the same for the third node, the data should also be the same.
docker exec -it mongorep3 mongoshmyrepl [direct: secondary] test> use mynewdbmyrepl [direct: secondary] test> db.people.find()[{_id: ObjectId("63a08880e1c97fba6959ec15"),name: 'John Rambo',occupation: 'Soldier'}]
No comments:
Post a Comment