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
3. 重启每个容器
- docker restart mongo1 mongo2 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加一行: 127.0.0.1 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
来源:oschina
链接:https://my.oschina.net/u/2414912/blog/4521228