A mongo replica set in 4 simple steps using docker
Installing a mongo replica-set in four steps:
1. docker container definition
Mongo instance which will part of the replica-set, Dockerfile
:
FROM mongo
EXPOSE 27017
CMD ["mongod", "--replSet", "my-mongo-set"]
2. stack setup
Stack via docker-compose.yml
:
version: "3"
services:
mongo1:
build: .
ports:
- "0.0.0.0:30001:27017"
networks:
- my_mongo_cluster
mongo2:
build: .
ports:
- "0.0.0.0:30002:27017"
networks:
- my_mongo_cluster
mongo3:
build: .
ports:
- "0.0.0.0:30003:27017"
networks:
- my_mongo_cluster
networks:
my_mongo_cluster:
driver: bridge
3. startup
Run: docker-compose build
4. setup replica set
Connect with python and initialize replica set:
>>> from pymongo import MongoClient
>>> c1 = MongoClient('mongodb://192.168.1.63:30001')
>>> c1.admin.command('replSetInitiate', {"_id" : "my-mongo-set","members" : [
{"_id" : 0,"host" : "192.168.1.63:30001"},
{"_id" : 1,"host" : "192.168.1.63:30002"},
{"_id" : 2,"host" : "192.168.1.63:30003"}]})
< {u'$clusterTime': {u'clusterTime': Timestamp(1604424245, 1),
u'signature': {u'keyId': 0L,
u'hash': Binary('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
, 0)}},
u'ok': 1.0, u'operationTime': Timestamp(1604424245, 1)}
>>>
You need to have installed pymongo(*) and connect in this case to one of the instances running. In my case, 192.168.1.63 is the local docker host network address.
(*) pip install --user pymongo
5. connecting to replica-set
To connect to replica-set and use its features you must let it know the config, like using this db-url:
mongodb://192.168.1.63:30001,192.168.1.63:30002,192.168.1.63:30003/?replicaSet=my-mongo-set
See ya!