mongodb cluster
1. 创建外挂目录并授权
mkdir -p /home/mongo1/db /home/mongo1/log
mkdir -p /home/mongo2/db /home/mongo2/log
mkdir -p /home/mongo3/db /home/mongo3/log
chmod 755
2. 拉取最新mongodb
docker pull mongo
3. 创建副本集结点
docker run -itd --name=mongo1 -p 27001:27017 --restart=always \
-v /home/mongo1/db:/data/db \
-v /home/mongo1/log:/data/log \
mongo --replSet "rs" --bind_ip_all
docker run -itd --name=mongo2 -p 27002:27017 --restart=always \
-v /home/mongo2/db:/data/db \
-v /home/mongo2/log:/data/log \
mongo --replSet "rs" --bind_ip_all
docker run -itd --name=mongo3 -p 27003:27017 --restart=always \
-v /home/mongo3/db:/data/db \
-v /home/mongo3/log:/data/log \
mongo --replSet "rs" --bind_ip_all
4. 追加参数 限制内存(根据物理内存而定,防止mongo)
docker container update -m 3000M --memory-swap -1 mongo1
docker container update -m 1000M --memory-swap -1 mongo2
docker container update -m 1000M --memory-swap -1 mongo3
5. 查看内部地址
docker inspect mongo1 | grep IPAddress
6. 登录数据库
docker exec -it mongo1 /bin/bash
mongosh
7. 副本集初始化
host为数据库所在的地址,可以用主机名替换,如在
rs.initiate( {
_id : "rs",
members: [
{"_id": 0, "host": "192.168.0.104:27001" },
{"_id": 1, "host": "192.168.0.104:27002" },
{"_id": 2, "host": "192.168.0.104:27003" }
]
})
8. 重新初始化
conf = rs.conf()
conf.members[0].host="host1:27001";
conf.members[1].host="host2:27002";
conf.members[2].host="host3:27003";
rs.reconfig(conf);
9. 设置复本集数据库的主优先集,priority值越大 优先选为主
cfg=rs.conf()
cfg.members[0].priority=2
rs.reconfig(cfg)
10. 增加、删除节点
#增加节点
rs.add({"_id":3,"host":"192.168.0.104:27011"})
rs.add({"_id":3,"host":"192.168.0.104:27004"})
#删除节点
rs.remove("192.168.0.104:27001")
11. 创建数据库并授权
use admin
db.auth('admin','123456')
use testdb
db.createUser({user:'root',pwd:'123456',roles:[{role:'dbAdmin',db:'testdb'}]});
db.grantRolesToUser("root",[{role:"readWrite",db:"testdb"}])
12.查看结果