一、副本集(主从复制)
1、docker-compose.yml
version: '3'
services:
mongo1:
image: mongo
container_name: mongo1
command: mongod --replSet rs0 --port 27017
volumes:
- ./mongodb-cluster/mongod1:/data/db
ports:
- "27017:27017"
networks:
- weiji-net
mongo2:
image: mongo
container_name: mongo2
command: mongod --replSet rs0 --port 27018
volumes:
- ./mongodb-cluster/mongod2:/data/db
ports:
- "27018:27017"
networks:
- weiji-net
mongo3:
image: mongo
container_name: mongo3
command: mongod --replSet rs0 --port 27019
volumes:
- ./mongodb-cluster/mongod3:/data/db
ports:
- "27019:27017"
networks:
- weiji-net
networks:
weiji-net:
external: true
name: app_net
2、初始化副本集
进入mongodb容器中
docker exec -it mongo1 mongo
初始化副本集(rs0)
var cfg = {"_id": "rs0","members": [{"_id": 0,"host": "mongo1:27017","priority": 2},{"_id": 1,"host": "mongo2:27018","priority": 1},{"_id": 2,"host": "mongo3:27019","priority": 0}]};
rs.initiate(cfg, { force: true }); # 初始化副本集。force: true 强制初始化
rs.reconfig(cfg, { force: true }); # 重新配置副本集
rs.secondaryOk(); # 允许在次要节点上执行读操作
rs.status(); # 获取副本集的当前状态,包括主节点(PRIMARY)、次要节点(SECONDARY)
db.getMongo().setReadPref('nearest'); # 设置读偏好为 "nearest",这意味着MongoDB将尝试从就近的节点读取数据,以降低延迟
db.getMongo().setSecondaryOk(); # 允许在次要节点上执行读操作
3、测试
连接
你也可以使用mongodb客户端工具连接主节点或命令行进入
docker exec -it mongo2 mongosh --host mongo2:27018
增加数据
use test
db.testCollection.insert({ message: "Hello, MongoDB" })
db.testCollection.find()
检查数据是否同步
当你从主节点进入容器后,可以直接查询到新增的数据,当从从节点进入后需要手动开启“读偏好”,否则会报错“not master and slaveOk=false”
db.getMongo().setReadPref("primaryPreferred");
use test
db.testCollection.find()