---
# System prepended metadata

title: mongodb replication 指令

---

# mongodb replication 指令

流程：
1. sudo service mongod stop
2. sudo rm -r -f /var/lib/mongodb-rs-a
先把舊的資料夾刪掉
3. sudo mkdir -p /var/lib/mongodb-rs-a
存放mongoDB data的資料夾
4. sudo chown -R mongodb:mongodb /var/lib/mongodb-rs-a
5. sudo nano /etc/mongod.conf

![](https://hackmd.io/_uploads/Byp-YbE42.png)

6. sudo service mongod restart
7. mongosh mongodb://192.168.56.176

目前三台虛擬機都一樣

primary:
rs.initiate()
rs.conf()
rs.add("第二台ip:port")
rs.add("第三台ip:port")

再來到另外兩台
rs.secondaryOk()是在secondary上執行，會報warning，但不管它

這樣就能讀取DB資料

回到primary，設定priority：
cfg = rs.conf()
cfg.members[0].priority = 4 //primary
cfg.members[1].priority = 2 //backup
rs.reconfig(cfg)

以上設定完就完成了DB同步。

ref:
https://ithelp.ithome.com.tw/articles/10266428
https://hevodata.com/learn/mongodb-replica-set-config/
https://blog.toright.com/posts/4508/mongodb-replica-set-%E9%AB%98%E5%8F%AF%E7%94%A8%E6%80%A7%E6%9E%B6%E6%A7%8B%E6%90%AD%E5%BB%BA.html
https://www.mongodb.com/docs/manual/tutorial/force-member-to-be-primary/

