第183集MongoDB云化部署与1主1从架构 | 字数总计: 3.6k | 阅读时长: 19分钟 | 阅读量:
1. MongoDB云化部署概述 MongoDB云化部署是将传统MongoDB架构迁移到云端环境,利用云平台的优势实现弹性扩展、高可用性和运维自动化。1主1从副本集架构是MongoDB云化部署中最常用的高可用方案,既保证了数据安全,又实现了读写分离。
1.1 MongoDB云化部署优势
弹性扩展 : 根据业务需求动态调整资源
高可用性 : 云平台提供的基础设施保障
运维自动化 : 减少人工运维成本
成本优化 : 按需付费,降低总体成本
安全可靠 : 云平台的安全防护机制
监控完善 : 云平台提供的监控和告警服务
1.2 MongoDB副本集特点
主节点 : 处理所有写操作和读操作
从节点 : 复制主节点数据,提供数据备份
自动故障转移 : 主节点故障时从节点自动提升
数据同步 : 实时数据同步保证一致性
读写分离 : 支持从从节点读取数据
1.3 MongoDB云化部署架构类型
容器化部署 : 使用Docker容器部署MongoDB
Kubernetes部署 : 使用K8s管理MongoDB副本集
云服务部署 : 使用云平台提供的MongoDB服务
混合云部署 : 结合公有云和私有云
2. Docker容器化部署 2.1 Docker镜像构建 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 FROM mongo:6.0 RUN apt-get update && apt-get install -y \ curl \ vim \ && rm -rf /var/lib/apt/lists/* RUN groupadd -r mongodb && useradd -r -g mongodb mongodb RUN mkdir -p /data/db && chown -R mongodb:mongodb /data COPY mongod.conf /etc/mongod.conf COPY entrypoint.sh /usr/local/bin/entrypoint.sh RUN chmod +x /usr/local/bin/entrypoint.sh USER mongodbEXPOSE 27017 ENTRYPOINT ["/usr/local/bin/entrypoint.sh" ] CMD ["mongod" , "--config" , "/etc/mongod.conf" ]
2.2 MongoDB主节点配置 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 storage: dbPath: /data/db journal: enabled: true wiredTiger: engineConfig: cacheSizeGB: 1 collectionConfig: blockCompressor: snappy indexConfig: prefixCompression: true systemLog: destination: file logAppend: true path: /var/log/mongodb/mongod.log logRotate: reopen net: port: 27017 bindIp: 0.0 .0 .0 processManagement: fork: false pidFilePath: /var/run/mongodb/mongod.pid replication: replSetName: "rs0" security: authorization: enabled keyFile: /etc/mongodb/keyfile
2.3 MongoDB从节点配置 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 storage: dbPath: /data/db journal: enabled: true wiredTiger: engineConfig: cacheSizeGB: 1 collectionConfig: blockCompressor: snappy indexConfig: prefixCompression: true systemLog: destination: file logAppend: true path: /var/log/mongodb/mongod.log logRotate: reopen net: port: 27017 bindIp: 0.0 .0 .0 processManagement: fork: false pidFilePath: /var/run/mongodb/mongod.pid replication: replSetName: "rs0" security: authorization: enabled keyFile: /etc/mongodb/keyfile
2.4 Docker Compose部署 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 version: '3.8' services: mongodb-master: build: . container_name: mongodb-master ports: - "27017:27017" volumes: - mongodb-master-data:/data/db - ./mongod-master.conf:/etc/mongod.conf - ./keyfile:/etc/mongodb/keyfile environment: - MONGO_INITDB_ROOT_USERNAME=admin - MONGO_INITDB_ROOT_PASSWORD=admin123 - MONGO_INITDB_DATABASE=admin networks: - mongodb-network restart: unless-stopped healthcheck: test: ["CMD" , "mongosh" , "--eval" , "db.adminCommand('ping')" ] interval: 30s timeout: 10s retries: 3 mongodb-slave: build: . container_name: mongodb-slave ports: - "27018:27017" volumes: - mongodb-slave-data:/data/db - ./mongod-slave.conf:/etc/mongod.conf - ./keyfile:/etc/mongodb/keyfile environment: - MONGO_INITDB_ROOT_USERNAME=admin - MONGO_INITDB_ROOT_PASSWORD=admin123 - MONGO_INITDB_DATABASE=admin depends_on: - mongodb-master networks: - mongodb-network restart: unless-stopped healthcheck: test: ["CMD" , "mongosh" , "--eval" , "db.adminCommand('ping')" ] interval: 30s timeout: 10s retries: 3 volumes: mongodb-master-data: mongodb-slave-data: networks: mongodb-network: driver: bridge
2.5 启动脚本 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 #!/bin/bash set -eif [ "$MONGO_ROLE " = "slave" ]; then echo "Waiting for master to be ready..." while ! mongosh --host mongodb-master --port 27017 --eval "db.adminCommand('ping')" > /dev/null 2>&1; do echo "Waiting for master..." sleep 2 done echo "Master is ready, starting slave..." fi exec "$@ "
3. Kubernetes部署方案 3.1 MongoDB主节点Deployment 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 apiVersion: apps/v1 kind: Deployment metadata: name: mongodb-master labels: app: mongodb role: master spec: replicas: 1 selector: matchLabels: app: mongodb role: master template: metadata: labels: app: mongodb role: master spec: containers: - name: mongodb image: mongo:6.0 ports: - containerPort: 27017 env: - name: MONGO_INITDB_ROOT_USERNAME value: "admin" - name: MONGO_INITDB_ROOT_PASSWORD value: "admin123" volumeMounts: - name: mongodb-data mountPath: /data/db - name: mongodb-config mountPath: /etc/mongod.conf subPath: mongod.conf - name: mongodb-keyfile mountPath: /etc/mongodb/keyfile subPath: keyfile resources: requests: memory: "1Gi" cpu: "500m" limits: memory: "2Gi" cpu: "1000m" livenessProbe: exec: command: - mongosh - --eval - "db.adminCommand('ping')" initialDelaySeconds: 30 periodSeconds: 10 readinessProbe: exec: command: - mongosh - --eval - "db.adminCommand('ping')" initialDelaySeconds: 5 periodSeconds: 5 volumes: - name: mongodb-data persistentVolumeClaim: claimName: mongodb-master-pvc - name: mongodb-config configMap: name: mongodb-master-config - name: mongodb-keyfile secret: secretName: mongodb-keyfile
3.2 MongoDB从节点Deployment 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 apiVersion: apps/v1 kind: Deployment metadata: name: mongodb-slave labels: app: mongodb role: slave spec: replicas: 1 selector: matchLabels: app: mongodb role: slave template: metadata: labels: app: mongodb role: slave spec: containers: - name: mongodb image: mongo:6.0 ports: - containerPort: 27017 env: - name: MONGO_INITDB_ROOT_USERNAME value: "admin" - name: MONGO_INITDB_ROOT_PASSWORD value: "admin123" volumeMounts: - name: mongodb-data mountPath: /data/db - name: mongodb-config mountPath: /etc/mongod.conf subPath: mongod.conf - name: mongodb-keyfile mountPath: /etc/mongodb/keyfile subPath: keyfile resources: requests: memory: "1Gi" cpu: "500m" limits: memory: "2Gi" cpu: "1000m" livenessProbe: exec: command: - mongosh - --eval - "db.adminCommand('ping')" initialDelaySeconds: 30 periodSeconds: 10 readinessProbe: exec: command: - mongosh - --eval - "db.adminCommand('ping')" initialDelaySeconds: 5 periodSeconds: 5 volumes: - name: mongodb-data persistentVolumeClaim: claimName: mongodb-slave-pvc - name: mongodb-config configMap: name: mongodb-slave-config - name: mongodb-keyfile secret: secretName: mongodb-keyfile
3.3 Service配置 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 apiVersion: v1 kind: Service metadata: name: mongodb-master-service labels: app: mongodb role: master spec: ports: - port: 27017 targetPort: 27017 protocol: TCP selector: app: mongodb role: master type: ClusterIP --- apiVersion: v1 kind: Service metadata: name: mongodb-slave-service labels: app: mongodb role: slave spec: ports: - port: 27017 targetPort: 27017 protocol: TCP selector: app: mongodb role: slave type: ClusterIP
3.4 ConfigMap配置 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 apiVersion: v1 kind: ConfigMap metadata: name: mongodb-master-config data: mongod.conf: | storage: dbPath: /data/db journal: enabled: true wiredTiger: engineConfig: cacheSizeGB: 1 collectionConfig: blockCompressor: snappy indexConfig: prefixCompression: true systemLog: destination: file logAppend: true path: /var/log/mongodb/mongod.log logRotate: reopen net: port: 27017 bindIp: 0.0 .0 .0 processManagement: fork: false pidFilePath: /var/run/mongodb/mongod.pid replication: replSetName: "rs0" security: authorization: enabled keyFile: /etc/mongodb/keyfile --- apiVersion: v1 kind: ConfigMap metadata: name: mongodb-slave-config data: mongod.conf: | storage: dbPath: /data/db journal: enabled: true wiredTiger: engineConfig: cacheSizeGB: 1 collectionConfig: blockCompressor: snappy indexConfig: prefixCompression: true systemLog: destination: file logAppend: true path: /var/log/mongodb/mongod.log logRotate: reopen net: port: 27017 bindIp: 0.0 .0 .0 processManagement: fork: false pidFilePath: /var/run/mongodb/mongod.pid replication: replSetName: "rs0" security: authorization: enabled keyFile: /etc/mongodb/keyfile
3.5 Secret配置 1 2 3 4 5 6 7 8 apiVersion: v1 kind: Secret metadata: name: mongodb-keyfile type: Opaque data: keyfile: <base64-encoded-keyfile-content>
4. 副本集配置与管理 4.1 副本集初始化 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 rs.initiate ({ _id : "rs0" , members : [ { _id : 0 , host : "mongodb-master-service:27017" , priority : 2 }, { _id : 1 , host : "mongodb-slave-service:27017" , priority : 1 } ] }); rs.status (); rs.conf ();
4.2 副本集管理命令 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 rs.add ("mongodb-new-service:27017" ); rs.remove ("mongodb-old-service:27017" ); rs.reconfig ({ _id : "rs0" , members : [ { _id : 0 , host : "mongodb-master-service:27017" , priority : 2 }, { _id : 1 , host : "mongodb-slave-service:27017" , priority : 1 } ] }); rs.stepDown ();
4.3 读写分离配置 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 db.adminCommand ({ replSetStepDown : 0 , secondaryCatchUpPeriodSecs : 10 }); db.setReadPreference ("secondaryPreferred" ); db.setWriteConcern ({ w : "majority" , j : true , wtimeout : 5000 });
5. 云平台部署方案 5.1 阿里云MongoDB部署 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 aliyun dds CreateDBInstance \ --DBInstanceClass "dds.mongo.mid" \ --DBInstanceDescription "mongodb-master-slave" \ --Engine "MongoDB" \ --EngineVersion "4.4" \ --RegionId "cn-hangzhou" \ --ZoneId "cn-hangzhou-h" \ --VpcId "vpc-xxx" \ --VSwitchId "vsw-xxx" \ --AccountPassword "MongoDB123456" \ --ReplicationFactor "2" aliyun dds CreateReplicaSet \ --DBInstanceId "dds-xxx" \ --ReplicaSetName "rs0" \ --ReplicaSetMembers "mongodb-master,mongodb-slave"
5.2 腾讯云MongoDB部署 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 tccli mongodb CreateDBInstance \ --ZoneId 100003 \ --TypeId 2 \ --Memory 1024 \ --Volume 100 \ --GoodsNum 1 \ --Period 1 \ --Password "MongoDB123456" \ --BillingMode 1 \ --VpcId "vpc-xxx" \ --SubnetId "subnet-xxx" \ --ProjectId 0 \ --AutoRenew 1 \ --MongoVersion "4.4" \ --ReplicateSetNum 2
5.3 AWS DocumentDB部署 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 aws docdb create-db-cluster \ --db-cluster-identifier "mongodb-cluster" \ --engine "docdb" \ --master-username "admin" \ --master-user-password "MongoDB123456" \ --vpc-security-group-ids "sg-xxx" \ --db-subnet-group-name "mongodb-subnet-group" \ --backup-retention-period 7 \ --preferred-backup-window "03:00-04:00" \ --preferred-maintenance-window "sun:04:00-sun:05:00" aws docdb create-db-instance \ --db-instance-identifier "mongodb-master" \ --db-cluster-identifier "mongodb-cluster" \ --db-instance-class "db.t3.medium" \ --engine "docdb"
6. 云端监控与运维 6.1 Prometheus监控配置 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 global: scrape_interval: 15s scrape_configs: - job_name: 'mongodb-master' static_configs: - targets: ['mongodb-master-service:27017' ] metrics_path: /metrics scrape_interval: 10s - job_name: 'mongodb-slave' static_configs: - targets: ['mongodb-slave-service:27017' ] metrics_path: /metrics scrape_interval: 10s
6.2 MongoDB Exporter配置 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 apiVersion: apps/v1 kind: Deployment metadata: name: mongodb-exporter spec: replicas: 1 selector: matchLabels: app: mongodb-exporter template: metadata: labels: app: mongodb-exporter spec: containers: - name: mongodb-exporter image: percona/mongodb_exporter:latest ports: - containerPort: 9216 env: - name: MONGODB_URI value: "mongodb://admin:admin123@mongodb-master-service:27017/admin" resources: requests: memory: "128Mi" cpu: "100m" limits: memory: "256Mi" cpu: "200m"
6.3 Grafana仪表板配置 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 { "dashboard" : { "title" : "MongoDB 1主1从监控" , "panels" : [ { "title" : "MongoDB连接数" , "type" : "graph" , "targets" : [ { "expr" : "mongodb_connections_current" , "legendFormat" : "{{instance}}" } ] } , { "title" : "MongoDB内存使用" , "type" : "graph" , "targets" : [ { "expr" : "mongodb_memory_resident_megabytes" , "legendFormat" : "{{instance}}" } ] } , { "title" : "MongoDB操作数" , "type" : "graph" , "targets" : [ { "expr" : "mongodb_opcounters_total" , "legendFormat" : "{{instance}} - {{type}}" } ] } , { "title" : "副本集状态" , "type" : "graph" , "targets" : [ { "expr" : "mongodb_replset_member_state" , "legendFormat" : "{{instance}} - {{member}}" } ] } ] } }
6.4 告警规则配置 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 groups: - name: mongodb rules: - alert: MongoDBDown expr: mongodb_up == 0 for: 1m labels: severity: critical annotations: summary: "MongoDB instance is down" description: "MongoDB instance {{ $labels.instance }} is down" - alert: MongoDBHighMemoryUsage expr: mongodb_memory_resident_megabytes / mongodb_memory_virtual_megabytes > 0.8 for: 5m labels: severity: warning annotations: summary: "MongoDB high memory usage" description: "MongoDB instance {{ $labels.instance }} memory usage is above 80%" - alert: MongoDBHighConnections expr: mongodb_connections_current > 1000 for: 5m labels: severity: warning annotations: summary: "MongoDB high connections" description: "MongoDB instance {{ $labels.instance }} has too many connections" - alert: MongoDBReplicaSetDown expr: mongodb_replset_member_state != 1 for: 2m labels: severity: critical annotations: summary: "MongoDB replica set member down" description: "MongoDB replica set member {{ $labels.member }} is down"
6.5 自动化运维脚本 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 #!/bin/bash check_mongodb_status () { local host=$1 local port=$2 local username=$3 local password=$4 if mongosh --host $host --port $port --username $username --password $password --eval "db.adminCommand('ping')" > /dev/null 2>&1; then echo "MongoDB $host :$port is healthy" return 0 else echo "MongoDB $host :$port is unhealthy" return 1 fi } failover_mongodb () { local master_host=$1 local master_port=$2 local username=$3 local password=$4 echo "Starting failover process..." if ! check_mongodb_status $master_host $master_port $username $password ; then echo "Master is down, checking replica set status..." mongosh --host $master_host --port $master_port --username $username --password $password --eval "rs.status()" echo "Replica set failover completed" return 0 else echo "Master is healthy, no failover needed" return 1 fi } backup_mongodb () { local host=$1 local port=$2 local username=$3 local password=$4 local database=$5 local backup_dir=$6 echo "Starting backup process..." mkdir -p $backup_dir mongodump --host $host :$port --username $username --password $password --db $database --out $backup_dir echo "Backup completed: $backup_dir " } restore_mongodb () { local host=$1 local port=$2 local username=$3 local password=$4 local database=$5 local backup_dir=$6 echo "Starting restore process..." mongorestore --host $host :$port --username $username --password $password --db $database $backup_dir /$database echo "Restore completed" } main () { case $1 in "check" ) check_mongodb_status $2 $3 $4 $5 ;; "failover" ) failover_mongodb $2 $3 $4 $5 ;; "backup" ) backup_mongodb $2 $3 $4 $5 $6 $7 ;; "restore" ) restore_mongodb $2 $3 $4 $5 $6 $7 ;; *) echo "Usage: $0 {check|failover|backup|restore} [args...]" exit 1 ;; esac } main "$@ "
7. 云端安全配置 7.1 网络安全配置 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: mongodb-network-policy spec: podSelector: matchLabels: app: mongodb policyTypes: - Ingress - Egress ingress: - from: - podSelector: matchLabels: app: application ports: - protocol: TCP port: 27017 egress: - to: - podSelector: matchLabels: app: mongodb ports: - protocol: TCP port: 27017
7.2 访问控制配置 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 use admin db.createUser ({ user : "admin" , pwd : "admin123" , roles : [ { role : "userAdminAnyDatabase" , db : "admin" }, { role : "readWriteAnyDatabase" , db : "admin" }, { role : "dbAdminAnyDatabase" , db : "admin" }, { role : "clusterAdmin" , db : "admin" } ] }); use myapp db.createUser ({ user : "appuser" , pwd : "app123" , roles : [ { role : "readWrite" , db : "myapp" } ] }); use myapp db.createUser ({ user : "readonly" , pwd : "read123" , roles : [ { role : "read" , db : "myapp" } ] });
7.3 加密传输配置 1 2 3 4 5 6 7 8 9 net: port: 27017 bindIp: 0.0 .0 .0 tls: mode: requireTLS certificateKeyFile: /etc/ssl/mongodb.pem CAFile: /etc/ssl/ca.pem allowConnectionsWithoutCertificates: false
8. 性能优化策略 8.1 云端资源优化 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 resources: requests: memory: "2Gi" cpu: "1000m" limits: memory: "4Gi" cpu: "2000m" apiVersion: autoscaling/v2 kind: HorizontalPodAutoscaler metadata: name: mongodb-hpa spec: scaleTargetRef: apiVersion: apps/v1 kind: Deployment name: mongodb-slave minReplicas: 1 maxReplicas: 3 metrics: - type: Resource resource: name: cpu target: type: Utilization averageUtilization: 70
8.2 存储优化 1 2 3 4 5 6 7 8 9 10 11 12 apiVersion: storage.k8s.io/v1 kind: StorageClass metadata: name: fast-ssd provisioner: kubernetes.io/aws-ebs parameters: type: gp3 iops: "3000" throughput: "125" volumeBindingMode: WaitForFirstConsumer allowVolumeExpansion: true
8.3 索引优化 1 2 3 4 5 6 7 8 9 10 11 12 db.users .createIndex ({ "email" : 1 }, { unique : true }); db.users .createIndex ({ "name" : 1 , "age" : -1 }); db.users .createIndex ({ "location" : "2dsphere" }); db.users .aggregate ([ { $indexStats : {} } ]); db.users .find ({ "name" : "John" }).explain ("executionStats" );
9. 故障处理与恢复 9.1 云端故障检测 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 #!/bin/bash check_cloud_service () { local service=$1 local region=$2 case $service in "aws" ) aws docdb describe-db-clusters --region $region ;; "aliyun" ) aliyun dds DescribeDBInstances --RegionId $region ;; "tencent" ) tccli mongodb DescribeInstances --Region $region ;; esac } auto_recovery () { local service=$1 local instance_id=$2 echo "Starting auto recovery for $service instance $instance_id " case $service in "aws" ) aws docdb reboot-db-instance --db-instance-identifier $instance_id ;; "aliyun" ) aliyun dds RestartDBInstance --DBInstanceId $instance_id ;; "tencent" ) tccli mongodb RestartInstance --InstanceId $instance_id ;; esac }
9.2 数据恢复策略 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 restore_mongodb_data () { local backup_file=$1 local target_host=$2 local target_port=$3 local username=$4 local password=$5 local database=$6 echo "Restoring data from $backup_file to $target_host :$target_port " mongosh --host $target_host --port $target_port --username $username --password $password --eval "db.adminCommand('shutdown')" scp -r $backup_file $target_host :/data/backup/ mongorestore --host $target_host --port $target_port --username $username --password $password --db $database /data/backup/$database mongod --config /etc/mongod.conf echo "Data restore completed" }
10. 最佳实践总结 10.1 云化部署原则
高可用优先 : 确保服务持续可用
弹性扩展 : 支持动态资源调整
安全可靠 : 加强安全防护
监控完善 : 全面监控集群状态
自动化运维 : 减少人工干预
10.2 1主1从架构优势
简单可靠 : 架构简单,易于维护
成本适中 : 相比集群模式成本较低
性能良好 : 读写分离提升性能
故障恢复 : 自动故障转移机制
数据安全 : 多副本保证数据安全
10.3 云端部署建议
选择合适云平台 : 根据业务需求选择
合理配置资源 : 避免资源浪费
加强监控告警 : 及时发现和处理问题
定期备份数据 : 保证数据安全
优化网络配置 : 提升网络性能
通过合理的MongoDB云化部署和1主1从副本集架构设计,可以构建稳定、高性能的云端MongoDB系统,满足企业级应用的需求。