使用Replica Set 的方式部署mongodb,这里我们部署一个primary,两个secondary,一个client:
首先搭建一个network bridge
docker network create mongo-network
然后再运行3个mongo容器,创建的集群名称是:mongo-rep
docker run --rm -itd --name mongo-primary --net=mongo-network mongo --replSet mongo-rep
docker run --rm -itd --name mongo-secondary1 --net=mongo-network mongo --replSet mongo-rep
docker run --rm -itd --name mongo-secondary2 --net=mongo-network mongo --replSet mongo-rep
docker run --rm -itd --name mongo-client --net=mongo-network mongo
查看4个容器的IP地址
docker network inspect mongo-network
结果为:
进入mongo客户端mongo-client,进行集群配置:
docker exec -it mongo-client mongo
> config = {_id:"mongo-rep", version:1, members:[{_id:0, host:"172.18.0.2:27017", priority:6}, {_id:1, host:"172.18.0.3:27017", priority:3}, {_id:2, host:"172.18.0.4:27017", priority:2}]}
配置结果:
{
"_id" : "mongo-rep",
"version" : 1,
"members" : [
{
"_id" : 0,
"host" : "172.18.0.2:27017",
"priority" : 6
},
{
"_id" : 1,
"host" : "172.18.0.3:27017",
"priority" : 3
},
{
"_id" : 2,
"host" : "172.18.0.4:27017",
"priority" : 2
}
]
}
激活配置:
rs.initiate(config)
输出结果:
{
"ok" : 1,
"$clusterTime" : {
"clusterTime" : Timestamp(1598946237, 1),
"signature" : {
"hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
"keyId" : NumberLong(0)
}
},
"operationTime" : Timestamp(1598946237, 1)
}
分别进入三个mongo集群容器:
docker exec -it mongo-primary mongo
docker exec -it mongo-secondary1 mongo
docker exec -it mongo-secondary2 mongo
显示结果:
将mongo-primary关闭之后,两个secondary节点中有一个节点会自动成为primary节点,
docker stop mongo-primary
如下图所示:
再将mongo-primary节点启动起来,mongo-secondary1节点又会变成secondary,如下图所示: