Mongodb 副本集的节点详细操作

本文详细介绍了MongoDB副本集的管理和操作,包括添加、移除节点,配置优先级和投票权,以及如何处理主节点选举和数据同步等问题。通过实际示例,深入解析了rs.add、rs.reconfig、rs.remove等关键命令的使用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

副本集操作

官方文档:https://docs.mongodb.com/v3.2/reference/method/js-replication/

1 rs.add()
{
_id: <int>,
host: <string>, // required
arbiterOnly: <boolean>,
buildIndexes: <boolean>,
hidden: <boolean>,
priority: <number>,
tags: <document>,
slaveDelay: <int>,
votes: <number>
}

Add a Secondary to a New Replica Set //添加一个新节点到新的副本集
rs.add( { host: "mongodbd4.example.net:27017" } )
rs.add( "mongodbd4.example.net:27017" )

Add a Secondary to an Existing Replica Set//添加一个新节点到已经存在的副本集
rs.add( { host: "mongodbd4.example.net:27017", priority: 0, votes: 0 } )
rs.status()

Reconfigure the replica set to update the votes and priority of the new member //配置副本集的投票属性
var cfg = rs.conf();
cfg.members[n].priority = 1; // Substitute the correct array index for the new member
cfg.members[n].votes = 1; // Substitute the correct array index for the new member
rs.reconfig(cfg)

WARNING //使用rs.reconfig()命令后,当前的主节点会down掉并发生选举
The rs.reconfig() shell method can force the current primary to step down, which causes an election. When the primary steps down,
the mongod closes all client connections. While this typically takes 10-20 seconds, try to make these changes during scheduled maintenance periods.
Avoid reconfiguring replica sets that contain members of different MongoDB versions as validation rules may differ across MongoDB versions.

Add a Priority 0 Member to a Replica Set //加入新节点,优先级为0
rs.add( { host: "mongodbd4.example.net:27017", priority: 0 } )
Add an Arbiter to a Replica Set //加入仲裁节点
rs.add( { host: "10.15.7.114:28003", arbiterOnly: true } )
添加备份节点
hidden(成员用于支持专用功能):这样设置后此机器在读写中都不可见,并且不会被选举为Primary,但是可以投票,一般用于备份数据
MyMongo:PRIMARY> rs.remove("10.15.7.114:28005"); #删除原来的第二个仲裁节点
MyMongo:PRIMARY> rs.add({host:"10.15.7.114:28005","priority":0,"hidden":true}) #设置为备份节点

添加延迟节点
Delayed(成员用于支持专用功能):可以指定一个时间延迟从primary节点同步数据。主要用于处理误删除数据马上同步到从节点导致的不一致问题
MyMongo:PRIMARY> rs.add({host:"10.15.7.114:28005","priority":0,"hidden":true,"slaveDelay":60})

Secondary-Only:不能成为primary节点,只能作为secondary副本节点,防止一些性能不高的节点成为主节点。
Non-Voting:没有选举权的secondary节点,纯粹的备份数据节点

2 rs.addArb()
rs.addArb(host) Adds a new arbiter to an existing replica set
WARNING//一般来说,避免在一个副本集中部署多个仲裁节点
In general, avoid deploying more than one arbiter per replica set

3 rs.conf()
//查看副本集配置信息
Returns a document that contains the current replica set configuration.
rs.config()
rs.config() is an alias of rs.conf().

4 rs.freeze()
rs.freeze(seconds)
//是当前副本集在指定时间内不能成为主节点(阻止选举)
Makes the current replica set member ineligible to become primary for the period specified

5 rs.help()
//返回副本集的一些函数
Returns a basic help text for all of the replication related shell functions.
MyMongo:PRIMARY> rs.help()
rs.status() { replSetGetStatus : 1 } checks repl set status
rs.initiate() { replSetInitiate : null } initiates set with default settings
rs.initiate(cfg) { replSetInitiate : cfg } initiates set with configuration cfg
rs.conf() get the current configuration object from local.system.replset
rs.reconfig(cfg) updates the configuration of a running replica set with cfg (disconnects)
rs.add(hostportstr) add a new member to the set with default attributes (disconnects)
rs.add(membercfgobj) add a new member to the set with extra attributes (disconnects)
rs.addArb(hostportstr) add a new member which is arbiterOnly:true (disconnects)
rs.stepDown([stepdownSecs, catchUpSecs]) step down as primary (disconnects)
rs.syncFrom(hostportstr) make a secondary sync from the given member
rs.freeze(secs) make a node ineligible to become primary for the time specified
rs.remove(hostportstr) remove a host from the replica set (disconnects)
rs.slaveOk() allow queries on secondary nodes

rs.printReplicationInfo() check oplog size and time range
rs.printSlaveReplicationInfo() check replica set members and replication lag
db.isMaster() check who is primary

reconfiguration helpers disconnect from the database so the shell will display
an error, even if the command succeeds.

6 rs.initiate()
rs.initiate(configuration) //初始化副本集
Initiates a replica set. Optionally, the method can take an argument in the form of a document that holds the configuration of a replica set.
Eg
rs.initiate(
{
_id: "myReplSet",
version: 1,
members: [
{ _id: 0, host : "mongodb0.example.net:27017" },
{ _id: 1, host : "mongodb1.example.net:27017" },
{ _id: 2, host : "mongodb2.example.net:27017" }
]
}
)

7 rs.printReplicationInfo()
//打印副本集的信息,这里为oplog日志
The following example is a sample output from the rs.printReplicationInfo() method run on the primary:
MyMongo:PRIMARY> rs.printReplicationInfo()
configured oplog size: 1024MB
log length start to end: 14939secs (4.15hrs)
oplog first event time: Thu Oct 11 2018 03:45:19 GMT+0800 (CST)
oplog last event time: Thu Oct 11 2018 07:54:18 GMT+0800 (CST)
now: Thu Oct 11 2018 07:54:23 GMT+0800 (CST)
MyMongo:PRIMARY> db.getReplicationInfo
//在slave上运行,命令为db.printSlaveReplicationInfo()
If run on a slave of a master-slave replication, the method calls db.printSlaveReplicationInfo().

8 rs.printSlaveReplicationInfo()
//返回slave与primary的延时
Returns a formatted report of the status of a replica set from the perspective of the secondary member of the set.
MyMongo:SECONDARY> rs.printSlaveReplicationInfo()
source: 10.15.7.114:28002
syncedTo: Thu Oct 11 2018 08:00:08 GMT+0800 (CST)
0 secs (0 hrs) behind the primary

9 rs.reconfig()
rs.reconfig(configuration, force) //{ force: true }
//重新配置已经存在的副本集,重写副本集配置文件,必须在primary节点上运行
Reconfigures an existing replica set, overwriting the existing replica set configuration. To run the method, you must connect to the primary of the replica set.
//重新配置副本集,必须先rs.conf(),在运行新的副本集配置,然后rs.reconfig()
To reconfigure an existing replica set, first retrieve the current configuration with rs.conf(), modify the configuration
document as needed, and then pass the modified document to rs.reconfig().

WARNING//避免在同一个副本集中,出现不同mongodb的版本
Avoid reconfiguring replica sets that contain members of different MongoDB versions as validation rules may differ across MongoDB versions.
//在执行命令rs.reconfig(),primary库会set down,进行重新选举
{ force: true }
WARNING//在执行rs.reconfig()加上force=ture参数,可导致提交的写操作回滚,要小心使用
Using rs.reconfig() with { force: true } can lead to rollback of committed writes. Exercise caution when using this option
Member Priority and Votes
Changed in version 3.2.
Members with priority greater than 0 cannot have 0 votes.
Non-voting members must have priority of 0.
##修改1为主节点,进行重新选举
cfg = rs.conf();
cfg.members[1].priority = 2;
rs.reconfig(cfg);

10 rs.remove()
rs.remove(hostname) //移除副本集成员
MyMongo:PRIMARY> rs.remove("10.15.7.114:28003");

11 rs.slaveOk()
MyMongo:SECONDARY> db.getMongo().setSlaveOk()
//允许在secondry节点上进行读取操作
This allows the current connection to allow read operations to run on secondary members.

12 rs.status()
//返回副本集的当前状态信息
This output reflects the current status of the replica set, using data derived from the heartbeat packets sent by the other members of the replica set.

13 rs.stepDown()
rs.stepDown(stepDownSecs, secondaryCatchUpPeriodSecs)
//此操作将会把primary节点变为secondry,并落后新成为primary节点%秒
Triggers the primary of the replica set to become a secondary. This in turn triggers an election for primary.
The method steps down the primary for a specified number of seconds; during this period, the stepdown member is ineligible from becoming primary.
主节点降为secondary
MyMongo:PRIMARY> use admin
MyMongo:PRIMARY> rs.stepDown(60)#单位为 秒
secondaryCatchUpPeriodSecs //Optional. The number of seconds that mongod will wait for an electable secondary to catch up to the primary.

14 rs.syncFrom()
//临时指定成员要同步的目标
which allows administrators to temporarily override the default sync target for the current member.
Specify the name of the member you want to replicate from in the form of [hostname]:[port].
rs.syncFrom("myHost:27017");

PRIMARY> rs.status().members[1].MyMongo

 

转载于:https://www.cnblogs.com/yhq1314/p/10001284.html

<think>好的,我现在要帮助用户解决MongoDB副本添加节点失败的问题。首先,我需要回忆一下用户提到的错误场景,可能有哪些常见原因导致添加副本节点失败。用户可能遇到了网络问题、配置错误、认证问题或者数据同步失败等情况。 首先,用户可能需要检查网络连接。副本成员之间的通信是否正常,端口是否开放,防火墙有没有阻止。比如,MongoDB默认使用27017端口,但副本成员之间可能还需要其他端口通信,所以用户需要确认这些端口是否都被允许。 接下来是配置问题。用户的mongod.conf文件是否正确配置了replication.replSetName,确保所有节点副本名称一致。另外,bindIp设置是否正确,是否允许其他节点的IP连接。这里可能需要检查bindIp是否包含其他节点的IP或者设置为0.0.0.0(虽然不建议生产环境这样做,但测试时可以尝试)。 然后是认证方面。如果启用了密钥文件或RBAC,新节点必须使用相同的密钥文件,并且有足够的权限。用户可能需要检查新节点的密钥文件权限是否为400,以及文件内容是否和其他节点一致。此外,新节点的用户权限是否允许加入副本,比如clusterAdmin角色是否被正确分配。 数据同步也是一个常见问题。如果新节点的数据目录有旧数据,可能会导致同步失败。用户可能需要清除新节点的数据目录,并重新启动mongod服务。另外,主节点和新增节点之间的MongoDB版本是否一致,版本差异可能导致兼容性问题。 查看日志是关键步骤。用户需要检查新节点的mongod.log,寻找错误信息,比如连接拒绝、认证失败、配置不匹配等。日志通常会给出具体的错误原因,例如“replSetInitiate error”或“Authentication failed”。 如果用户是通过rs.add()命令添加节点,可能需要检查命令参数是否正确,比如主机名和端口是否正确,是否使用了正确的IP地址(如果是内网IP,需要确保其他节点可以解析)。有时DNS解析问题也会导致添加失败,使用IP地址代替主机名可能更可靠。 另外,副本节点数量限制需要注意,MongoDB副本最多支持50个成员,但只有7个投票成员。如果用户已经添加了很多节点,可能需要调整配置。 还有可能遇到的情况是,主节点当前是否有足够的资源处理新的同步请求,比如磁盘空间、内存是否足够。如果主节点负载过高,可能导致添加新节点时超时或失败。 最后,用户可能需要逐步验证每一步,从网络连通性开始,逐步检查配置、认证、数据目录、日志,最后再尝试重新添加节点。如果所有步骤都正确,可能需要重启mongod服务或者重新配置副本。 总结下来,用户需要系统性地排查网络、配置、认证、数据同步以及日志中的具体错误信息,从而找到导致添加节点失败的根本原因,并针对性地解决。</think>在MongoDB副本中添加新节点失败时,可按照以下步骤排查问题: --- ### **一、网络连接检查** 1. **端口连通性** - 确保新节点与现有副本成员之间的`27017`端口(或自定义端口)双向互通 - 使用命令测试:`telnet <目标IP> 27017` 或 `nc -zv <目标IP> 27017` - ❗ 防火墙/Security Group需放行相关端口 2. **DNS解析** - 副本配置建议使用**静态IP**而非主机名(避免DNS解析问题) - 临时测试:在`/etc/hosts`中手动添加IP与主机名映射 --- ### **二、配置一致性验证** 1. **关键配置项** 检查新节点的`mongod.conf`是否包含: ```yaml replication: replSetName: "your_replset_name" # 必须与现有副本名称完全一致 security: keyFile: /path/to/keyfile # 若启用认证,密钥文件需与现有节点相同 ``` 2. **密钥文件权限** ```bash chmod 400 /path/to/keyfile # 必须设置权限为400 ``` --- ### **三、认证与权限问题** 1. **同步密钥文件** - 将现有副本的密钥文件**完整复制**到新节点相同路径 - 确保文件内容通过`md5sum`校验一致 2. **管理员权限** 连接到主节点执行: ```javascript db.getSiblingDB("admin").createUser({ user: "replUser", pwd: "password", roles: [{ role: "clusterAdmin", db: "admin" }] }) ``` --- ### **四、数据同步失败处理** 1. **清除旧数据** - 停止新节点MongoDB服务 - 删除数据目录:`rm -rf /var/lib/mongodb/*` - 重启服务后重新加入副本 2. **查看同步状态** 在主节点执行: ```javascript rs.status().members.forEach(m => printjson({id: m._id, name: m.name, stateStr: m.stateStr})) ``` - 观察新节点的`stateStr`是否为`STARTUP2`(同步中)或`SECONDARY` --- ### **五、日志分析** 1. **关键日志路径** - 检查新节点的`/var/log/mongodb/mongod.log` - 重点关注以下错误类型: ```log # 认证失败 [conn12345] Authentication failed # 配置不匹配 replSet error member x.x.x.x has conflicting replSet names # 网络超时 Failed to connect to x.x.x.x:27017, reason: Connection refused ``` --- ### **六、强制重新配置(谨慎操作)** 若配置混乱可尝试重置副本
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值