使用Docker方式部署Mongodb多副本集(replSet)

linux主机ip:192.168.0.253

1. 创建网络与容器

docker pull mongo
docker network create mongo-rs
docker run --name mongo1 -p 27027:27027 --net mongo-rs -d mongo mongod --replSet "rs0" --port 27027
docker run --name mongo2 -p 27028:27028 --net mongo-rs -d mongo mongod --replSet "rs0" --port 27028
docker run --name mongo3 -p 27029:27029 --net mongo-rs -d mongo mongod --replSet "rs0" --port 27029

2. 分别进入每个容器执行

docker exec -it mongo1 /bin/bash
echo "127.0.0.1 mongo1 mongo2 mongo3" >> /etc/hosts

docker exec -it mongo2 /bin/bash
echo "127.0.0.1 mongo1 mongo2 mongo3" >> /etc/hosts

docker exec -it mongo3 /bin/bash
echo "127.0.0.1 mongo1 mongo2 mongo3" >> /etc/hosts

3. 重启每个容器

docker restart mongo1 
docker restart mongo2
docker restart mongo3

4. 进入一个容器初始化副本集:

docker exec -it mongo1 mongo --port 27027
rs.initiate({"_id": "rs0", "members": [{"_id":0, "host":  "mongo1:27027"}, {"_id": 1, "host": "mongo2:27028"}, {"_id":2, "host":  "mongo3:27029"}]})

5. 添加本地环境hosts:

  • Linux用户在本地/etc/hosts文件中添加 127.0.0.1 mongo1 mongo2 mongo3
  • Windows 用户在hosts加一行:192.168.0.253 mongo1 mongo2 mongo3

6. Application连接

  • mongodb://127.0.0.1:27027,127.0.0.1:27028,127.0.0.1:27029/databaseName?slaveOk=true&replicaSet=rs0&write=1&connectTimeoutMS=30000&readPreference=primary
  • mongodb://192.168.0.253:27027,192.168.0.253:27028,192.168.0.253:27029/databaseName?slaveOk=true&replicaSet=rs0&write=1&connectTimeoutMS=30000&readPreference=primary

7. Navicat连接

posted @ 2020-11-06 15:52  哈喽哈喽111111  阅读(1421)  评论(1编辑  收藏  举报