Docs 菜单

Docs 主页开发应用程序MongoDB Manual

使用数据库转储备份分片集群

要使用 mongodump对分片集群进行一致备份,您必须首先停止负载均衡器,停止写入,并停止集群上的任何模式转换操作。 这可确保集群在备份期间保持一致状态。

MongoDB 提供的备份和恢复操作可以与负载均衡器一起运行,并通过以下服务运行事务:

  • MongoDB Atlas

  • MongoDB Cloud Manager

  • MongoDB Ops Manager

此任务使用mongodump备份分片集群。确保您正在运行的集群包含分片集合中的数据。

此过程需要支持mongos的 fsync 锁定的 MongoDB 版本。

从 MongoDB 7开始。 0 。 2 (也可从6 . 0 . 11和5 . 0 . 22开始), fsyncfsyncUnlock命令可在mongos上运行以锁定并解锁分片集群。

要执行这些任务,您的用户必须具有fsync授权,该授权允许用户运行fsyncfsyncUnlock命令。

要对分片集群进行自我管理备份,请完成以下步骤:

1

要找到执行备份的最佳时间,请监控应用程序和数据库使用情况,找到不太可能发生数据段迁移、重新分片和模式转换操作的时间,因为这些操作可能会导致备份不一致。

有关更多信息,请参阅为分片集群安排备份窗口。

2

为防止数据段迁移扰乱备份,请连接到mongos并使用sh.stopBalancer()方法停止负载均衡器:

sh.stopBalancer()

如果正在进行均衡轮次,则操作会等待均衡完成。

要确认负载均衡器已停止,请使用sh.getBalancerState()方法:

sh.getBalancerState()
false

当负载均衡器停止时,该命令会返回false

3

分片集群必须在备份过程中保持锁定状态,以保护数据库免遭写入,写入可能会导致备份不一致。

要锁定分片集群,请连接到mongos并使用db.fsyncLock()方法:

db.getSiblingDB("admin").fsyncLock()

要确认锁定,请在配置服务器的mongos和主mongod上运行以下聚合管道并确保所有分片均已锁定:

db.getSiblingDB("admin").aggregate( [
{ $currentOp: { } },
{ $facet: {
"locked": [
{ $match: { $and: [
{ fsyncLock: { $exists: true } },
{ fsyncLock: true }
] } }],
"unlocked": [
{ $match: { fsyncLock: { $exists: false } } }
]
} },
{ $project: {
"fsyncLocked": { $gt: [ { $size: "$locked" }, 0 ] },
"fsyncUnlocked": { $gt: [ { $size: "$unlocked" }, 0 ] }
} }
] )
[ { fsyncLocked: true }, { fsyncUnlocked: false } ]
4

要备份分片集群,请使用mongodump连接到mongos并执行备份:

mongodump \
--host mongos.example.net \
--port 27017 \
--username user \
--password "passwd" \
--out /opt/backups/example-cluster-1
5

备份完成后,您可以解锁集群以允许恢复写入。

要解锁集群,请使用db.fsyncUnlock()方法:

db.getSibling("admin").fsyncUnlock()

要确认解锁,请在mongos和配置服务器的主mongod上运行以下聚合管道并确保所有分片均已解锁:

db.getSiblingDB("admin").aggregate( [
{ $currentOp: { } },
{ $facet: {
"locked": [
{ $match: { $and: [
{ fsyncLock: { $exists: true } },
{ fsyncLock: true }
] } }],
"unlocked": [
{ $match: { fsyncLock: { $exists: false } } }
]
} },
{ $project: {
"fsyncLocked": { $gt: [ { $size: "$locked" }, 0 ] },
"fsyncUnlocked": { $gt: [ { $size: "$unlocked" }, 0 ] }
} }
] )
[ { fsyncLocked: false }, { fsyncUnlocked: true } ]
6

要重新启动负载均衡器,请使用sh.startBalancer()方法:

sh.startBalancer()

要确认负载均衡器正在运行,请使用sh.getBalancerState()方法:

sh.getBalancerState()
true

当负载均衡器正在运行时,该命令会返回true

您可以使用 从mongodump mongorestore备份恢复数据库。

  • 要恢复分片集群,请对 执行mongorestore mongos

  • 要迁移到副本集或独立服务器,请对 执行mongorestore mongod

有关更多信息,请参阅使用 MongoDB 工具进行备份和恢复。

← 使用文件系统快照备份分片集群