温馨提示×

mongodb debian如何集群

小樊
43
2026-09-26 15:43:35
栏目: 云计算

在 Debian 上部署 MongoDB 集群,通常指三种模式之一:

  1. 副本集(Replica Set)——高可用(最常用)
  2. 分片集群(Sharded Cluster)——大数据水平扩展
  3. 单机多实例(测试用)

下面我以 Debian 11/12 + MongoDB 7.x 为例,分别说明副本集和分片集群的部署方式。


一、Debian 安装 MongoDB(所有节点都要做)

1. 添加 MongoDB 官方源

sudo apt update
sudo apt install -y curl gnupg
curl -fsSL https://pgp.mongodb.com/server-7.0.asc | \
  sudo gpg -o /usr/share/keyrings/mongodb-server-7.0.gpg --dearmor

echo "deb [ signed-by=/usr/share/keyrings/mongodb-server-7.0.gpg ] \
https://repo.mongodb.org/apt/debian $(lsb_release -cs)/mongodb-org/7.0 main" | \
sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list

2. 安装 MongoDB

sudo apt update
sudo apt install -y mongodb-org

二、副本集(Replica Set)集群(推荐)

架构示例

节点 IP
node1 192.168.1.11
node2 192.168.1.12
node3 192.168.1.13

1. 修改配置文件

编辑 /etc/mongod.conf(所有节点)

net:
  bindIp: 0.0.0.0
  port: 27017

replication:
  replSetName: rs0

⚠️ 生产环境建议 bindIp 改为具体 IP

2. 启动服务

sudo systemctl enable mongod
sudo systemctl start mongod

3. 初始化副本集(只在主节点执行)

mongo
rs.initiate({
  _id: "rs0",
  members: [
    { _id: 0, host: "192.168.1.11:27017" },
    { _id: 1, host: "192.168.1.12:27017" },
    { _id: 2, host: "192.168.1.13:27017" }
  ]
})

查看状态:

rs.status()

三、分片集群(Sharded Cluster)

架构示例

角色 节点
Config Server 3 台
Shard 每组 3 台(副本集)
Mongos 1~2 台

1. Config Server(副本集)

sharding:
  clusterRole: configsvr
replication:
  replSetName: cfgrs

初始化:

rs.initiate({
  _id: "cfgrs",
  configsvr: true,
  members: [...]
})

2. Shard(副本集)

sharding:
  clusterRole: shardsvr
replication:
  replSetName: shard1

3. Mongos

sharding:
  configDB: cfgrs/192.168.1.21:27019,192.168.1.22:27019,192.168.1.23:27019

启动:

mongos --config /etc/mongos.conf

4. 添加分片

sh.addShard("shard1/192.168.1.31:27018,192.168.1.32:27018,192.168.1.33:27018")

四、防火墙 & 安全建议

sudo ufw allow 27017
sudo ufw allow 27019
  • 启用 auth
  • 使用 keyfile
  • 不要暴露公网

五、常见错误

  • not master → 没初始化副本集
  • node not reachable → 防火墙 / bindIp 错误
  • could not find member → IP 不一致

如果你愿意,我可以:

  • 给你 docker-compose 版 MongoDB 集群
  • 给你 生产级配置文件模板
  • 帮你设计 3 节点高可用方案

你打算用哪种集群?

0 踩