在Debian系统上搭建和管理MongoDB集群涉及多个步骤,包括安装MongoDB、配置副本集和分片、以及管理集群。以下是详细的步骤:
sudo apt update
sudo apt install -y mongodb-org
sudo systemctl enable --now mongod
mongo --eval 'db.runCommand({ connectionStatus: 1 })'
rs.initiate({
_id: "rs0",
members: [
{ _id: 0, host: "node1:27017" },
{ _id: 1, host: "node2:27017" },
{ _id: 2, host: "node3:27017", arbiterOnly: true }
]
})
rs.add("node1:27017")
rs.add("node2:27017")
rs.add("node3:27017")
mongos --configdb rs0/node1:27017,node2:27017,node3:27017
sh.addShard("shard1/node1:27001,node2:27001,node3:27001")
sh.addShard("shard2/node1:27002,node2:27002,node3:27002")
sh.addShard("shard3/node1:27003,node2:27003,node3:27003")
sh.enableSharding("test")
sh.shardCollection("test.table1", { "id": 1 })
mongo --eval 'db.printReplicationInfo()'
备份集群:
使用mongodump
工具进行备份。
恢复集群:
使用mongorestore
工具进行恢复。
用户管理: 创建管理员账号:
use admin
db.createUser({
user: "admin",
pwd: "password",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
})
mongod.conf
中启用认证:security:
authorization: enabled
重启MongoDB服务使更改生效。