高可用性是指您的应用程序在基础设施服务中断、系统维护和其他干扰期间,确保持续操作并最大限度地减少停机时间的能力。MongoDB 的默认部署架构专为高可用性而设计,具有内置的数据冗余和自动故障转移功能。
高可用性 与 灾难恢复 不同。高可用性可防止节点、区域、地区或云提供商服务中断等基础设施故障,通过自动故障转移,可在故障发生的精确时刻进行恢复,且不会丢失数据(RPO = 0),并在几秒内完成 RTO。灾难恢复可以防止数据完整性问题,例如损坏或意外删除,这些问题需要从备份恢复。要了解有关灾难恢复的更多信息,请参阅 Atlas 灾难恢复指导。
本页描述了您可以选择的其他配置选项和部署架构增强,以防止服务中断并支持针对可用区、区域和云提供商服务中断的强大故障转移机制。
Atlas 高可用性功能
数据库复制
MongoDB's default deployment architecture is designed for redundancy. Atlas deploys each cluster as a replica set with a minimum of three database instances (also called nodes or replica set members), distributed across separate availability zones within your selected cloud provider regions. Applications write data to the replica set's primary node, and then Atlas replicates and stores that data across all nodes within your cluster. To control the durability of your data storage, you can adjust the write concern of your application code to complete the write only once a certain number of secondaries have committed the write. The default behavior is for data to be persisted on a majority of electable nodes before confirming the action.
下图表示默认三节点副本集的复制工作原理:

自动故障转移
In the event that a primary node in a replica set becomes unavailable due to an infrastructure outage, scheduled maintenance, or any other disruption, Atlas clusters self-heal by promoting an existing secondary node to the role of primary node in a replica set election. This failover process is fully automatic and recovers to the exact moment of failure with no data loss (RPO = 0) in seconds. Operations that were in flight at the time of the failure are retried after the failure if retryable writes are enabled. After a replica set election, Atlas restores or replaces the failing member to ensure that the cluster is returned to its target configuration as soon as possible. The MongoDB client driver also automatically switches all client connections during and after the failure.
下图表示副本集选举过程:

为了提高最关键应用程序的可用性,您可以通过添加节点、区域或云提供商来扩展部署,以分别抵御区、区域或提供商的服务中断。要了解更多信息,请参阅下面的扩展您的部署范式以实现容错建议。
关于 Atlas 高可用性的建议
以下建议描述了您可以使用的其他配置选项和部署架构增强,以提高部署的可用性。
选择适合您部署目标的集群层
您可以在“专用”、“灵活”或“免费”部署类型下提供的范围集群层中进行选择。MongoDB Atlas中的集群层指定了集群中每个节点可用的资源(内存、存储、vCPU 和 IOPS)。扩展到更高层级可提高集群处理流量峰值的能力,并通过更快地响应高工作负载来提高系统可靠性。要确定适合您的应用程序大小的推荐集群层,请参阅《Atlas集群大小指南》。
Atlas also supports auto-scaling to allow the cluster to automatically adjust to spikes in demand. Atlas uses both reactive auto-scaling, which triggers based on current resource usage, and predictive auto-scaling, which proactively scales up eligible clusters before forecasted cyclical demand spikes occur. Automating scaling actions reduces the risk of an outage due to resource constraints. To learn more, see Guidance for Atlas Automated Infrastructure Provisioning.
扩展您的部署范式以实现容错
An Atlas deployment's fault tolerance is the number of replica set members that can become unavailable while your deployment still remains operational. In the event of an availability zone, region, or cloud provider outage, Atlas clusters self-heal by promoting an existing secondary node to the role of primary node in a replica set election. A majority of the voting nodes in a replica set must be operational in order to run a replica set election when a primary node experiences an outage.
为确保副本集在部分区域服务中断时能够选举出主节点,您应将集群部署到至少有三个可用区的区域。可用区是单个云提供商区域内独立的数据中心组,每个数据中心都有自己的电力、冷却和网络基础设施。当您选择的云提供商区域支持可用区时,Atlas 会自动将您的集群分布在这些可用区中,以便在某个可用区发生服务中断时,集群中的其他节点仍然支持区域服务。大多数 Atlas 支持的云提供商区域至少有三个可用区。这些区域在 Atlas 用户界面中标记有星形图标。
每个云提供商都在可用区内提供默认数据冗余:
AWS 将数据存储在 AWS 区域中跨越至少三个可用区的多个设备上。
Microsoft Azure使用本地冗余存储(LRS),可在所选区域的单个数据中心内将数据复制三份。
Google Cloud 将数据分布在该区域的多个区域中。
For more information about recommended regions, see Cloud Providers and Regions.
为了进一步提高您最关键的应用程序的容错能力,您可以通过添加节点、区域或云提供商来扩展部署,以分别应对可用区、区域或提供商的服务中断。您可以将节点数增加到任意奇数,可选举节点数最多为 7 个,节点总数最多为 50 个。您还可以将集群部署到多个区域,以增强更大地理区域的可用性,并在发生全区域服务中断导致主区域内所有可用区禁用的情况下启用自动故障转移。同样的模式也适用于将您的集群部署到多个云提供商,以应对整个云提供商的服务中断。
有关如何选择能够平衡高可用性、低延迟、合规性和费用需求的部署的指导,请参阅我们的 Atlas 部署范式文档。
部署模式 RTO/RPO 权衡
下表比较了不同部署范例的 RTO 和 RPO 特征。在 majority写关注(write concern)下,所有这些方法都可以在几秒钟内实现 RPO = 0(无数据丢失)和 RTO。需要在部署复杂性和集群费用进行权衡。
部署范例 | 涵盖的故障场景 | 典型 RTO | RPO(多数写关注(write concern)) | 相对复杂性 | 相对集群费用 |
|---|---|---|---|---|---|
单区域部署(1地区中的 3 个节点) | 单个区域内的节点或可用区故障 | 秒(自动故障转移) | 0(无数据丢失) | 低 | $ |
多区域、单云 | 一个地理区域内的可用区或区域服务中断 | 秒(自动故障转移) | 0(无数据丢失) | 中型 | $$ |
多区域、多地理位置 | 跨多个地区的区域或地区服务中断 | 秒(自动故障转移) | 0(无数据丢失) | 中–高 | $$–$$$ |
多云(2–3 提供商) | 影响一个提供商的云提供商或多区域服务中断 | 秒(自动故障转移) | 0(无数据丢失) | 高 | $$$ |
防止意外删除集群
您可以启用终止保护,以确保集群不会被意外终止,并且不需要停机即可从备份恢复。要删除已启用终止保护的集群,必须先禁用终止保护。默认情况下,Atlas 会禁用所有集群的终止保护。
在使用 Terraform 等 IaC 工具时,终止保护尤为重要,以确保重新部署不会预配新的基础设施。
测试自动故障转移
We strongly recommend that you simulate various scenarios that require automatic node failovers to measure your preparedness for such events before you deploy an application to production. With Atlas, you can test primary node failover for a replica set and simulate regional outages for a multi-region deployment.
使用 majority 写关注
MongoDB allows you to specify the level of acknowledgment requested for write operations by using write concern. Atlas has a default write concern of majority, meaning that data must be replicated across more than half of the nodes in your cluster before Atlas reports success. Using majority instead of a definite number value like 2 allows Atlas to automatically adjust to requiring replication across fewer nodes if you experience a temporary node outage, allowing writes to continue after automatic failover. This also provides a consistent setting across all environments, so your connection string remains the same whether you have three nodes in a test environment or a larger number of nodes in production.
配置可重试的数据库读写操作
Atlas supports retryable read and retryable write operations. When enabled, Atlas retries read and write operations once as a safeguard against intermittent network outages and replica set elections in which the application temporarily cannot find a healthy primary node. Retryable writes require an acknowledged write concern, meaning your write concern cannot be {w: 0}.
监控和规划您的资源使用情况
To avoid resource capacity issues, we recommend that you monitor resource utilization and hold regular capacity planning sessions. MongoDB's Professional Services offers these sessions. See our Resource Capacity Disaster Recovery Plan for our recommendations on how to recover from resource capacity issues.
要了解资源利用警报和监控的最佳实践,请参阅 Atlas 监控和警报指导。
规划您的 MongoDB 版本更改
We recommend that you run the latest MongoDB version to take advantage of new features and improved security guarantees. You should always ensure that you upgrade to the latest MongoDB major version before your current version reaches end of life.
您无法使用 Atlas 用户界面降级 MongoDB 版本。因此,我们建议您在计划和执行主要版本升级时直接与 MongoDB 的Professional Services或技术服务合作,以帮助您避免在升级过程中可能出现的任何问题。
配置维护窗口
在计划维护期间,Atlas 通过滚动更新的方式逐一对节点进行更新,以保持正常运行时间。在此过程中,每当当前主节点因维护而离线时,Atlas 会通过自动副本集选举选出一个新的主节点。此过程与自动故障转移时的处理方式相同,用于应对主节点的非计划性中断。
We recommend that you configure a custom maintenance window for your project to avoid maintenance-related replica set elections during business-critical hours. You can also set protected hours in your maintenance window settings to define a daily window of time in which standard updates cannot begin. Standard updates do not involve cluster restarts or resyncs.
自动化示例:Atlas 高可用性
以下示例使用Atlas 工具配置单区域 3 节点副本集/分片部署拓扑结构以实现自动化。
这些示例还应用其他推荐的配置,包括:
集群层已为开发/测试环境设置为
M10。使用集群大小指南了解适合应用程序大小的推荐集群层。单区域,3 节点副本集/分片部署拓扑结构。
Our examples use AWS, Azure, and Google Cloud interchangeably. You can use any of these three cloud providers, but you must change the region name to match the cloud provider. To learn about the cloud providers and their regions, see Cloud Providers.
集群层已设置为
M30,适用于中型应用程序。使用集群大小指南了解适合应用程序大小的推荐集群层。单区域,3 节点副本集/分片部署拓扑结构。
Our examples use AWS, Azure, and Google Cloud interchangeably. You can use any of these three cloud providers, but you must change the region name to match the cloud provider. To learn about the cloud providers and their regions, see Cloud Providers.
为每个项目创建一个部署
在您的开发和测试环境中,为每个项目运行以下命令。在以下示例中,更改 ID 和名称以使用您的值。
注意
以下示例未启用自动伸缩功能,以帮助控制开发和测试环境中的费用。对于分阶段和生产环境,应启用自动伸缩功能。请参阅“分阶段环境和生产环境”标签页,以获取启用自动伸缩的示例。
atlas clusters create CustomerPortalDev \ --projectId 56fd11f25f23b33ef4c2a331 \ --region EASTERN_US \ --members 3 \ --tier M10 \ --provider GCP \ --mdbVersion 8.0 \ --diskSizeGB 30 \ --tag bu=ConsumerProducts \ --tag teamName=TeamA \ --tag appName=ProductManagementApp \ --tag env=dev \ --tag version=8.0 \ --tag email=marissa@example.com \ --watch
对于您的暂存环境和生产环境,请为每个项目创建以下 cluster.json 文件。更改 ID 和名称以使用您自己的值:
{ "clusterType": "REPLICASET", "links": [], "name": "CustomerPortalProd", "mongoDBMajorVersion": "8.0", "replicationSpecs": [ { "numShards": 1, "regionConfigs": [ { "electableSpecs": { "instanceSize": "M30", "nodeCount": 3 }, "priority": 7, "providerName": "GCP", "regionName": "EASTERN_US", "analyticsSpecs": { "nodeCount": 0, "instanceSize": "M30" }, "autoScaling": { "compute": { "enabled": true, "scaleDownEnabled": true }, "diskGB": { "enabled": true } }, "readOnlySpecs": { "nodeCount": 0, "instanceSize": "M30" } } ], "zoneName": "Zone 1" } ], "tag" : [{ "bu": "ConsumerProducts", "teamName": "TeamA", "appName": "ProductManagementApp", "env": "Production", "version": "8.0", "email": "marissa@example.com" }] }
在您创建 cluster.json 文件后,请为每个项目运行以下命令。该命令使用 cluster.json 文件来创建一个集群。
atlas cluster create --projectId 5e2211c17a3e5a48f5497de3 --file cluster.json
For more configuration options and info about this example, see the atlas clusters create command.
注意
在使用 Terraform 创建资源之前,您必须:
重要
以下示例使用 MongoDB Atlas Terraform 提供商版本 2.x(~> 2.2)。如果您正在从提供商版本 1.x 升级,请参阅 2.0.0 升级指南 了解破坏性变更和迁移步骤。这些示例使用带 v2.x 语法的mongodbatlas_advanced_cluster 资源。
创建项目和部署
对于您的开发和测试环境,请为每个应用程序和环境对创建以下文件。将每个应用程序和环境对的文件放在各自的目录中。更改 ID 和名称以使用您的值:
main.tf
# Create a Project resource "mongodbatlas_project" "atlas-project" { org_id = var.atlas_org_id name = var.atlas_project_name } # Create an Atlas Advanced Cluster resource "mongodbatlas_advanced_cluster" "atlas-cluster" { project_id = mongodbatlas_project.atlas-project.id name = "ClusterPortalDev" cluster_type = "REPLICASET" mongo_db_major_version = var.mongodb_version # MongoDB recommends enabling auto-scaling # When auto-scaling is enabled, Atlas may change the instance size, and this use_effective_fields # block prevents Terraform from reverting Atlas auto-scaling changes use_effective_fields = true replication_specs = [ { region_configs = [ { electable_specs = { instance_size = var.cluster_instance_size_name node_count = 3 } auto_scaling = { compute_enabled = true compute_scale_down_enabled = true compute_max_instance_size = "M60" compute_min_instance_size = "M10" } priority = 7 provider_name = var.cloud_provider region_name = var.atlas_region } ] } ] tags = { BU = "ConsumerProducts" TeamName = "TeamA" AppName = "ProductManagementApp" Env = "Test" Version = "8.0" Email = "marissa@example.com" } } # Outputs to Display output "atlas_cluster_connection_string" { value = mongodbatlas_advanced_cluster.atlas-cluster.connection_strings.0.standard_srv } output "project_name" { value = mongodbatlas_project.atlas-project.name }
注意
要创建多区域集群,请在各自的 region_configs 对象中指定每个区域,并将它们嵌套在 replication_specs 对象中。priority 字段必须按降序排列,并且必须包含介于 7 和 1 之间的值,如下例所示:
replication_specs = [ { region_configs = [ { electable_specs = { instance_size = "M10" node_count = 2 } auto_scaling = { compute_enabled = true compute_scale_down_enabled = true compute_max_instance_size = "M60" compute_min_instance_size = "M10" } provider_name = "GCP" priority = 7 region_name = "NORTH_AMERICA_NORTHEAST_1" }, { electable_specs = { instance_size = "M10" node_count = 3 } auto_scaling = { compute_enabled = true compute_scale_down_enabled = true compute_max_instance_size = "M60" compute_min_instance_size = "M10" } provider_name = "GCP" priority = 6 region_name = "WESTERN_US" } ] } ]
variables.tf
# MongoDB Atlas Provider Authentication Variables # Legacy API key authentication (backward compatibility) variable "mongodbatlas_public_key" { type = string description = "MongoDB Atlas API public key" sensitive = true } variable "mongodbatlas_private_key" { type = string description = "MongoDB Atlas API private key" sensitive = true } # Recommended: Service account authentication variable "mongodb_service_account_id" { type = string description = "MongoDB service account ID for authentication" sensitive = true default = null } variable "mongodb_service_account_key_file" { type = string description = "Path to MongoDB service account private key file" sensitive = true default = null } # Atlas Organization ID variable "atlas_org_id" { type = string description = "Atlas Organization ID" } # Atlas Project Name variable "atlas_project_name" { type = string description = "Atlas Project Name" } # Atlas Project Environment variable "environment" { type = string description = "The environment to be built" } # Cluster Instance Size Name variable "cluster_instance_size_name" { type = string description = "Cluster instance size name" } # Cloud Provider to Host Atlas Cluster variable "cloud_provider" { type = string description = "AWS or GCP or Azure" } # Atlas Region variable "atlas_region" { type = string description = "Atlas region where resources will be created" } # MongoDB Version variable "mongodb_version" { type = string description = "MongoDB Version" } # Atlas Group Name variable "atlas_group_name" { type = string description = "Atlas Group Name" }
terraform.tfvars
atlas_org_id = "32b6e34b3d91647abb20e7b8" atlas_project_name = "Customer Portal - Dev" environment = "dev" cluster_instance_size_name = "M10" cloud_provider = "AWS" atlas_region = "US_WEST_2" mongodb_version = "8.0"
provider.tf
# Define the MongoDB Atlas Provider terraform { required_providers { mongodbatlas = { source = "mongodb/mongodbatlas" version = "~> 2.2" } } required_version = ">= 1.0" } # Configure the MongoDB Atlas Provider provider "mongodbatlas" { # Legacy API key authentication (backward compatibility) public_key = var.mongodbatlas_public_key private_key = var.mongodbatlas_private_key # Recommended: Service account authentication # Uncomment and configure the following for service account auth: # service_account_id = var.mongodb_service_account_id # private_key_file = var.mongodb_service_account_key_file }
在您创建文件后,导航到每个应用程序和环境对的目录,并运行以下命令以初始化 Terraform:
terraform init
运行以下命令以查看 Terraform 计划:
terraform plan
Run the following command to create one project and one deployment for the application and environment pair. The command uses the files and the MongoDB & HashiCorp Terraform to create the projects and clusters:
terraform apply
当出现提示时,输入 yes 然后按 Enter 以应用配置。
对于您的暂存环境和生产环境,请为每个应用程序和环境对创建以下文件。将每个应用程序和环境对的文件放在各自的目录中。更改 ID 和名称以使用您自己的值:
main.tf
# Create a Group to Assign to Project resource "mongodbatlas_team" "project_group" { org_id = var.atlas_org_id name = var.atlas_group_name usernames = [ "user1@example.com", "user2@example.com" ] } # Create a Project resource "mongodbatlas_project" "atlas-project" { org_id = var.atlas_org_id name = var.atlas_project_name } # Assign the team to project with specific roles resource "mongodbatlas_team_project_assignment" "project_team" { project_id = mongodbatlas_project.atlas-project.id team_id = mongodbatlas_team.project_group.team_id role_names = ["GROUP_READ_ONLY", "GROUP_CLUSTER_MANAGER"] } # Create an Atlas Advanced Cluster resource "mongodbatlas_advanced_cluster" "atlas-cluster" { project_id = mongodbatlas_project.atlas-project.id name = "ClusterPortalProd" cluster_type = "REPLICASET" mongo_db_major_version = var.mongodb_version use_effective_fields = true replication_specs = [ { region_configs = [ { electable_specs = { instance_size = var.cluster_instance_size_name node_count = 3 disk_size_gb = var.disk_size_gb } auto_scaling = { disk_gb_enabled = var.auto_scaling_disk_gb_enabled compute_enabled = var.auto_scaling_compute_enabled compute_max_instance_size = var.compute_max_instance_size } priority = 7 provider_name = var.cloud_provider region_name = var.atlas_region } ] } ] tags = { BU = "ConsumerProducts" TeamName = "TeamA" AppName = "ProductManagementApp" Env = "Production" Version = "8.0" Email = "marissa@example.com" } } # Outputs to Display output "atlas_cluster_connection_string" { value = mongodbatlas_advanced_cluster.atlas-cluster.connection_strings.standard_srv } output "project_name" { value = mongodbatlas_project.atlas-project.name }
注意
要创建多区域集群,请在各自的 region_configs 对象中指定每个区域,并将它们嵌套在 replication_specs 对象中,如下例所示:
replication_specs = [ { region_configs = [ { electable_specs = { instance_size = "M10" node_count = 2 } provider_name = "GCP" priority = 7 region_name = "NORTH_AMERICA_NORTHEAST_1" }, { electable_specs = { instance_size = "M10" node_count = 3 } provider_name = "GCP" priority = 6 region_name = "WESTERN_US" } ] } ]
variables.tf
# MongoDB Atlas Provider Authentication Variables # Legacy API key authentication (backward compatibility) variable "mongodbatlas_public_key" { type = string description = "MongoDB Atlas API public key" sensitive = true } variable "mongodbatlas_private_key" { type = string description = "MongoDB Atlas API private key" sensitive = true } # Recommended: Service account authentication variable "mongodb_service_account_id" { type = string description = "MongoDB service account ID for authentication" sensitive = true default = null } variable "mongodb_service_account_key_file" { type = string description = "Path to MongoDB service account private key file" sensitive = true default = null } # Atlas Organization ID variable "atlas_org_id" { type = string description = "Atlas Organization ID" } # Atlas Project Name variable "atlas_project_name" { type = string description = "Atlas Project Name" } # Atlas Project Environment variable "environment" { type = string description = "The environment to be built" } # Cluster Instance Size Name variable "cluster_instance_size_name" { type = string description = "Cluster instance size name" } # Cloud Provider to Host Atlas Cluster variable "cloud_provider" { type = string description = "AWS or GCP or Azure" } # Atlas Region variable "atlas_region" { type = string description = "Atlas region where resources will be created" } # MongoDB Version variable "mongodb_version" { type = string description = "MongoDB Version" } # Atlas Group Name variable "atlas_group_name" { type = string description = "Atlas Group Name" }
terraform.tfvars
atlas_org_id = "32b6e34b3d91647abb20e7b8" atlas_project_name = "Customer Portal - Prod" environment = "prod" cluster_instance_size_name = "M30" cloud_provider = "AWS" atlas_region = "US_WEST_2" mongodb_version = "8.0" atlas_group_name = "Atlas Group"
provider.tf
# Define the MongoDB Atlas Provider terraform { required_providers { mongodbatlas = { source = "mongodb/mongodbatlas" version = "~> 2.2" } } required_version = ">= 1.0" } # Configure the MongoDB Atlas Provider provider "mongodbatlas" { # Legacy API key authentication (backward compatibility) public_key = var.mongodbatlas_public_key private_key = var.mongodbatlas_private_key # Recommended: Service account authentication # Uncomment and configure the following for service account auth: # service_account_id = var.mongodb_service_account_id # private_key_file = var.mongodb_service_account_key_file }
在您创建文件后,导航到每个应用程序和环境对的目录,并运行以下命令以初始化 Terraform:
terraform init
运行以下命令以查看 Terraform 计划:
terraform plan
Run the following command to create one project and one deployment for the application and environment pair. The command uses the files and the MongoDB & HashiCorp Terraform to create the projects and clusters:
terraform apply
当出现提示时,输入 yes 然后按 Enter 以应用配置。
有关此示例的更多配置选项和信息,请参阅 MongoDB & HashiCorp Terraform。