前一陣將三節點的副本集改成了單節點,但后面業務代碼出現問題:無法使用事務,因為事務只有在副本集上能用,單節點無法使用,故需要改回副本集模式,而我目前僅有一臺服務器,所以考慮在一臺服務器上通過容器部署三節點副本集
version: "3.8"
services:mongo1:image: mongo:5.0.31container_name: mongo1ports:- 27017:27017volumes:- mongo2:/data/db # 復用你原來的數據command: ["mongod", "--replSet", "rs0", "--bind_ip_all"]mongo2:image: mongo:5.0.31container_name: mongo2ports:- 27018:27017volumes:- mongo2_data2:/data/dbcommand: ["mongod", "--replSet", "rs0", "--bind_ip_all"]mongo3:image: mongo:5.0.31container_name: mongo3ports:- 27019:27017volumes:- mongo2_data3:/data/dbcommand: ["mongod", "--replSet", "rs0", "--bind_ip_all"]volumes:mongo2: # 原來的數據卷mongo2_data2:mongo2_data3:
這里需要注意,docker volume mongo2是保存有數據的volume,所以你需要把它指定為主節點
>>> docker exec -it mongo1 mongosh
cfg = {_id: "rs0",members: [{ _id: 0, host: "10.6.212.87:27017", priority: 2 },{ _id: 1, host: "10.6.212.87:27018", priority: 1 },{ _id: 2, host: "10.6.212.87:27019", priority: 0 }]
}
rs.reconfig(cfg, { force: true })
還有就是啟動mongo時,如果加上“–auth”參數,會報如下錯誤
Attaching to mongo1, mongo2, mongo3
mongo2 | BadValue: security.keyFile is required when authorization is enabled with replica sets
mongo2 | try 'mongod --help' for more information
mongo1 | BadValue: security.keyFile is required when authorization is enabled with replica sets
mongo1 | try 'mongod --help' for more information
mongo3 | BadValue: security.keyFile is required when authorization is enabled with replica sets
mongo3 | try 'mongod --help' for more information
mongo2 exited with code 2
mongo1 exited with code 2
mongo3 exited with code 2
解決起來有一些麻煩,所以我就干脆把–auth參數去掉了,但會存在安全風險。
還要注意,mongodb比較吃內存,所以在單服務器上要注意內存,不然會被docker停掉。