MongoDB 在 Linux 上的扩容实践
一、扩容总览与选择路径
二、垂直扩容 扩展磁盘与文件系统
db.serverStatus().storageEngine 或查看 /etc/mongod.conf 的 storage.dbPath。growpart /dev/sda 1;pvcreate → vgextend → lvextend → resize2fs/xfs_growfs。sudo systemctl restart mongod,df -h 确认挂载点容量已增加。storage.dbPath 后启动。storage.wiredTiger.engineConfig.cacheSizeGB)以更贴合内存与负载。df -h、mongostat、mongotop 观察空间与性能变化。dbPath 需保证目录权限与 SELinux/AppArmor 策略正确。三、水平扩容 副本集增加数据节点
replication.replSetName 与 keyFile(各节点一致),设置 bindIp 与网络互通。rs.add("host:port");如需只读扩展可添加 隐藏/延迟 节点(不在此详述)。rs.status()、rs.printSecondaryReplicationInfo() 确认 stateStr=SECONDARY 且复制滞后可接受。rs.remove("host:port")。四、水平扩容 分片集群添加分片
sh.addShard("newShardHost:port"),使用 sh.status() 校验。sh.enableSharding("db"),选择并设定 分片键 后执行 sh.shardCollection("db.coll", {shardKey: 1})。sh.moveChunk() 优化分布。sh.status()、各分片数据量与 balancer 状态,确保无异常迁移与热点。五、自动化与运维要点
rs.status()、sh.status() 与 df -h 的基线信息。mongodb://user:pwd@host1:27017,host2:27017/db?replicaSet=rs0&w=majority;分片通过 mongos 接入,避免直连分片。bindIp,并审计关键操作。