MongoDB数据库,单库、集群、Docker安装部署以及注意事项

MongoDB主、备复制集群

功能介绍:

1、MongoDB主备复制集群,不需要借助第三方服务,就能实现数据可靠性,当某个节点挂掉,可以重新选举出主节点;
2、MongoDB 主备复制集群提供了数据安全性,当节点宕机后,备份数据保证数据不丢失;
3、MongoDB 主备复制集群提供了高性能,可通过配置主从读写分离提高服务性能;

一主两从架构图:
在这里插入图片描述

概述:

三个成员副本集提供了足够的冗余,足以应对大多数网络分区和其他系统故障。这些副本集的容量也足以满足许多分布式读操作的需求。副本集的成员数应始终为奇数。这将确保选举顺利进行。

在以下三节点副本集中,主节点接受所有写入操作。然后,从节点复制 oplog 以应用于其数据集。
在这里插入图片描述

集群保证高可用,一致性功能简介:

故障转移,投票选举的发生时机:

  • 1、向副本集添加新节点,
  • 2、initiating a replica set,
  • 3、使用 rs.stepDown()rs.reconfig() 等方法执行副本集维护,并且
  • 4、从节点成员失去与主节点成员的连接的时间超过所配置的 timeout (默认为 10 秒)。

成功完成选举之前,副本集无法处理写入操作,MongoDB 驱动程序可检测到主节点丢失,并一次性自动重试某些写入操作,从而为自动故障转移和选举提供额外的内置处理功能。

MongoDB 仅支持副本集协议版本1 ( pv1 ),是一个选举机制

投票选举期间,数据库集群的操作状态:

1、镜像读取可减少由于中断或计划维护后主节点选举对系统的影响。在副本集发生故障转移后,接管成为新主节点的从节点会在新查询请求传入时避免了从节点在选举后需要重新获取所有数据的情况,从而提高了整体性能恢复速度。

原理就是:

  • 允许主节点将其接收到的操作(写操作)镜像到可选举从节点上的一部分数据,这些特定的从节点有更多更新的数据副本,从而提高选举后的性能恢复速度。-
  • 这些从节点已经部分地或完全地复制了主节点的写操作,所以它们的缓存已经预先加载了一些最新的数据。

2、副本集故障转移期间的回滚:

  • 主节点发生故障转移后,如果之前的主节点重新加入副本集,系统会检查并恢复之前该节点上已接受但未复制到从节点上的写操作,以确保数据的完整性和一致性。
  • createRollbackDataFiles 参数可控制是否在回滚期间创建回滚文件,MongoDB 会将回滚数据写入 BSON 文件。

3、当成员进入 ROLLBACK 状态时,MongoDB 会终止所有正在进行的用户操作。

网络分区、脑裂问题解决方式:

1、当网络问题解决后,只有选举出的新主节点才会处理新的写操作,确保数据一致性不受多个主节点影响。

2、一旦网络重新连接,节点会根据复制集协议Oplog(操作日志)的内容来同步未同步的数据变更。

3、MongoDB 使用 Oplog 记录所有的写操作,这使得在节点重新连接后,能够通过 Oplog 回放来应用在分区期间发生的所有写操作,从而保持数据的一致性。

4、MongoDB 的副本集具有自动健康检查和自我修复的能力。一旦网络分区解决,节点会自动尝试重新连接和同步,以确保整个副本集的健康状态和数据一致性。

一、部署环境介绍

1 服务器详情

1.1 服务器配置(示例)
信息
操作系统Red Hat Enterprise Linux Server release 7.8 (Maipo)
CPU1(Thread) × 1(Core) × 4(Socket)
内存84GB
磁盘40G
1.2 部署情况(示例)
服务器IPOS登录信息节点状态、部署服务及对应端口号
192.168.6.107mongod/mongodmongo主(27017)
192.168.6.108mongod/mongodmongo备(27017)
192.168.6.111mongod/mongodmongo备(27017)

2 版本

服务名称版本信息
MongoDB“6.0.16”

3 部署目录

名称目录位置
MongoDB数据库安装目录/usr/bin
MongoDB数据库数据目录/var/lib/mongo
MongoDB数据库日志目录/var/log/mongodb

二、安装环境准备

2.1、关闭防火墙

# 关闭防火墙和selinux
(root)
systemctl stop firewalld

systemctl disable firewalld

sed -ri '7s#enforcing#disabled#g'  /etc/selinux/config

setenforce 0

getenforce

2.2、更换为国内yum源(可以不做)

##修改yum源,添加镜像。
rpm -qa |grep yum |xargs rpm -e --nodeps 

wget https://mirrors.aliyun.com/centos/7/os/x86_64/Packages/yum-3.4.3-168.el7.centos.noarch.rpm
wget https://mirrors.aliyun.com/centos/7/os/x86_64/Packages/yum-metadata-parser-1.1.4-10.el7.x86_64.rpm
wget https://mirrors.aliyun.com/centos/7/os/x86_64/Packages/yum-plugin-fastestmirror-1.1.31-54.el7_8.noarch.rpm

rpm -ivh yum-3.4.3-168.el7.centos.noarch.rpm yum-metadata-parser-1.1.4-10.el7.x86_64.rpm yum-plugin-fastestmirror-1.1.31-54.el7_8.noarch.rpm

wget -O/etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo
wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo

# vim rhel-source.repo
[rhel-source]
name=Red Hat Enterprise Linux $releasever - $basearch - Source
baseurl=file:///mnt
enabled=1
gpgcheck=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-release

yum clean all && yum makecache

2.3 添加Docker安装包、mondodb的rpm包镜像资源库

##添加docker镜像库
yum-config-manager \
    --add-repo \
    https://mirrors.ustc.edu.cn/docker-ce/linux/centos/docker-ce.repo

##替换原来的url路径
sed -i 's|https://download.docker.com|https://mirrors.ustc.edu.cn/docker-ce|g' your_file.txt

## 添加mondodb的rpm包镜像库
vim /etc/yum.repos.d/mongodb-org-6.0.repo

[mongodb-org-6.0]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/9/mongodb-org/6.0/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://pgp.mongodb.com/server-6.0.asc

#安装yum工具包
yum install -y yum-utils

三、在三个节点上执行相同的安装操作(如果是安装单实例数据库,只需要在一个节点安装即可)

3.1、 获取MongoDB的rpm安装包

3.1.1、安装MongoDB的Server端
##获取安rpm包,不推荐使用yum源仓库,有些C库版本会不支持。
[root@postgres local]# pwd
/usr/local
[root@postgres local]# mkdir mongodb
[root@postgres mongodb]# wget  https://repo.mongodb.org/yum/redhat/7/mongodb-org/6.0/x86_64/RPMS/mongodb-org-server-6.0.16-1.el7.x86_64.rpm
--2024-07-20 09:40:24--  https://repo.mongodb.org/yum/redhat/7/mongodb-org/6.0/x86_64/RPMS/mongodb-org-server-6.0.16-1.el7.x86_64.rpm
Resolving repo.mongodb.org (repo.mongodb.org)... 18.65.185.40, 18.65.185.2, 18.65.185.80, ...
Connecting to repo.mongodb.org (repo.mongodb.org)|18.65.185.40|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 32660492 (31M)
Saving to: ‘mongodb-org-server-6.0.16-1.el7.x86_64.rpm’

100%[===========================================================>] 32,660,492  3.62MB/s   in 9.6s   

2024-07-20 09:40:37 (3.25 MB/s) - ‘mongodb-org-server-6.0.16-1.el7.x86_64.rpm’ saved [32660492/32660492]

[root@postgres mongodb]# ls
mongodb-org-server-6.0.16-1.el7.x86_64.rpm

##使用rpm安装server
[root@postgres mongodb]# rpm -i --nosignature mongodb-org-server-6.0.16-1.el7.x86_64.rpm
Created symlink from /etc/systemd/system/multi-user.target.wants/mongod.service to /usr/lib/systemd/system/mongod.service.
##启动服务
[root@postgres tmp]# systemctl start mongod
[root@postgres tmp]# systemctl status mongod
● mongod.service - MongoDB Database Server
   Loaded: loaded (/usr/lib/systemd/system/mongod.service; enabled; vendor preset: disabled)
   Active: active (running) since Sat 2024-07-20 10:02:00 CST; 9s ago
     Docs: https://docs.mongodb.org/manual
 Main PID: 4603 (mongod)
    Tasks: 31
   CGroup: /system.slice/mongod.service
           └─4603 /usr/bin/mongod -f /etc/mongod.conf

Jul 20 10:02:00 postgres systemd[1]: Started MongoDB Database Server.
Jul 20 10:02:00 postgres mongod[4603]: {"t":{"$date":"2024-07-20T02:02:00.396Z"},"s":"I",  "c":"CONTROL",  "id":7484500, "ctx":"-","msg":"Environment varia...to false"}
Hint: Some lines were ellipsized, use -l to show in full.

3.1.2、 安装MongoDB的Client端

##安装client端
[root@postgres mongodb]# rpm -i mongodb-mongosh-1.10.6.aarch64.rpm
error: Failed dependencies:
        ld-linux-aarch64.so.1()(64bit) is needed by mongodb-mongosh-1.10.6-1.el8.aarch64
        ld-linux-aarch64.so.1(GLIBC_2.17)(64bit) is needed by mongodb-mongosh-1.10.6-1.el8.aarch64
        libc.so.6(GLIBC_2.25)(64bit) is needed by mongodb-mongosh-1.10.6-1.el8.aarch64
        libdl.so.2(GLIBC_2.17)(64bit) is needed by mongodb-mongosh-1.10.6-1.el8.aarch64
        libm.so.6(GLIBC_2.17)(64bit) is needed by mongodb-mongosh-1.10.6-1.el8.aarch64
        libpthread.so.0(GLIBC_2.17)(64bit) is needed by mongodb-mongosh-1.10.6-1.el8.aarch64
        libresolv.so.2(GLIBC_2.17)(64bit) is needed by mongodb-mongosh-1.10.6-1.el8.aarch64
[root@postgres mongodb]# yum search error: Failed dependencies:
        ld-linux-aarch64.so.1()(64bit) is needed by mongodb-mongosh-1.10.6-1.el8.aarch64
        ld-linux-aarch64.so.1(GLIBC_2.17)(64bit) is needed by mongodb-mongosh-1.10.6-1.el8.aarch64
        libc.so.6(GLIBC_2.25)(64bit) is needed by mongodb-mongosh-1.10.6-1.el8.aarch64
        libdl.so.2(GLIBC_2.17)(64bit) is needed by mongodb-mongosh-1.10.6-1.el8.aarch64
        libm.so.6(GLIBC_2.17)(64bit) is needed by mongodb-mongosh-1.10.6-1.el8.aarch64
        libpthread.so.0(GLIBC_2.17)(64bit) is needed by mongodb-mongosh-1.10.6-1.el8.aarch64
        libresolv.so.2(GLIBC_2.17)(64bit) is needed by mongodb-mongosh-1.10.6-1.el8.aarch64Loaded plugins: langpacks, product-id, search-disabled-repos, subscription-manager
This system is not registered with an entitlement server. You can use subscription-manager to register.
========================================== Matched: Failed ==========================================
squid.x86_64 : The Squid proxy caching server
Warning: No matches found for: error:
Warning: No matches found for: dependencies:

[root@postgres mongodb]# yum search mongodb-mongosh
Loaded plugins: langpacks, product-id, search-disabled-repos, subscription-manager
This system is not registered with an entitlement server. You can use subscription-manager to register.
=================================== N/S matched: mongodb-mongosh ====================================
mongodb-mongosh.x86_64 : MongoDB Shell CLI REPL Package
mongodb-mongosh-shared-openssl11.x86_64 : MongoDB Shell CLI REPL Package
mongodb-mongosh-shared-openssl3.x86_64 : MongoDB Shell CLI REPL Package

  Name and summary matches only, use "search all" for everything.
[root@postgres mongodb]# yum install -y mongodb-mongosh
Loaded plugins: langpacks, product-id, search-disabled-repos, subscription-manager
This system is not registered with an entitlement server. You can use subscription-manager to register.
Resolving Dependencies
--> Running transaction check
---> Package mongodb-mongosh.x86_64 0:2.2.12-1.el8 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

=====================================================================================================
 Package                   Arch             Version                  Repository                 Size
=====================================================================================================
Installing:
 mongodb-mongosh           x86_64           2.2.12-1.el8             mongodb-org-7.0            56 M

Transaction Summary
=====================================================================================================
Install  1 Package

Total download size: 56 M
Installed size: 249 M
Downloading packages:
warning: /var/cache/yum/x86_64/7Server/mongodb-org-7.0/packages/mongodb-mongosh-2.2.12.x86_64.rpm: Header V4 RSA/SHA256 Signature, key ID 1785ba38: NOKEY
Public key for mongodb-mongosh-2.2.12.x86_64.rpm is not installed
mongodb-mongosh-2.2.12.x86_64.rpm                                             |  56 MB  00:00:18     
Retrieving key from https://pgp.mongodb.com/server-7.0.asc
Importing GPG key 0x1785BA38:
 Userid     : "MongoDB 7.0 Release Signing Key <packaging@mongodb.com>"
 Fingerprint: e588 3020 1f7d d82c d808 aa84 160d 26bb 1785 ba38
 From       : https://pgp.mongodb.com/server-7.0.asc
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
Warning: RPMDB altered outside of yum.
  Installing : mongodb-mongosh-2.2.12-1.el8.x86_64                                               1/1 
  Verifying  : mongodb-mongosh-2.2.12-1.el8.x86_64                                               1/1 

Installed:
  mongodb-mongosh.x86_64 0:2.2.12-1.el8                                                              

Complete!

3.2 使用mongosh连接服务器


##连接服务器
[root@postgres mongodb]# mongosh
Current Mongosh Log ID: 669b20d2cbf8954aa5482f8a
Connecting to:          mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+2.2.12
Using MongoDB:          6.0.16
Using Mongosh:          2.2.12

For mongosh info see: https://docs.mongodb.com/mongodb-shell/

------
   The server generated these startup warnings when booting
   2024-07-20T10:02:00.591+08:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
   2024-07-20T10:02:00.591+08:00: Journaling works best if /proc/sys/vm/overcommit_memory is set to 0 or 1
   2024-07-20T10:02:00.591+08:00: /sys/kernel/mm/transparent_hugepage/enabled is 'always'. We suggest setting it to 'never' in this binary version
   2024-07-20T10:02:00.591+08:00: /sys/kernel/mm/transparent_hugepage/defrag is 'always'. We suggest setting it to 'never' in this binary version
   2024-07-20T10:02:00.591+08:00: vm.max_map_count is too low
------


Deprecation warnings:
  - Using mongosh on the current operating system is deprecated, and support may be removed in a future release.
See https://www.mongodb.com/docs/mongodb-shell/install/#supported-operating-systems for documentation on supported platforms.
test> show collections;

查看配置信息

test> db.serverCmdLineOpts()
{
  argv: [ '/usr/bin/mongod', '-f', '/etc/mongod.conf' ],
  parsed: {
    config: '/etc/mongod.conf',
    net: { bindIp: '0.0.0.0', port: 27017 },
    processManagement: { timeZoneInfo: '/usr/share/zoneinfo' },
    storage: { dbPath: '/var/lib/mongo', journal: { enabled: true } },
    systemLog: {
      destination: 'file',
      logAppend: true,
      path: '/var/log/mongodb/mongod.log'
    }
  },
  ok: 1
}
test> 
test> show databases;
admin   40.00 KiB
config  60.00 KiB
local   40.00 KiB
mydb    40.00 KiB
test> use mydb
switched to db mydb
mydb> show connections;
MongoshInvalidInputError: [COMMON-10001] 'connections' is not a valid argument for "show".
mydb> show collections
products
mydb> db.products.find();
[
  {
    _id: 1,
    product_name: '手机',
    prices: [
      { date: ISODate('2023-01-01T00:00:00.000Z'), price: 1000 },
      { date: ISODate('2023-02-01T00:00:00.000Z'), price: 900 },
      { date: ISODate('2023-03-01T00:00:00.000Z'), price: 950 }
    ]
  },
  {
    _id: 2,
    product_name: '平板电脑',
    prices: [
      { date: ISODate('2023-01-01T00:00:00.000Z'), price: 1200 },
      { date: ISODate('2023-02-01T00:00:00.000Z'), price: 1100 },
      { date: ISODate('2023-03-01T00:00:00.000Z'), price: 1150 }
    ]
  },
  {
    _id: 3,
    product_name: '耳机',
    prices: [
      { date: ISODate('2023-01-01T00:00:00.000Z'), price: 200 },
      { date: ISODate('2023-02-01T00:00:00.000Z'), price: 180 },
      { date: ISODate('2023-03-01T00:00:00.000Z'), price: 190 }
    ]
  },
  {
    _id: 4,
    product_name: '智能手表',
    prices: [
      { date: ISODate('2023-01-01T00:00:00.000Z'), price: 500 },
      { date: ISODate('2023-02-01T00:00:00.000Z'), price: 480 },
      { date: ISODate('2023-03-01T00:00:00.000Z'), price: 490 }
    ]
  }
]
mydb> 

四、配置主、备库参数文档,启动服务

4.1、配置数据库主、备节点的参数文档

配置文件/etc/mongod.conf三个节点内容都是相同的,主要关注主要在于replication:net:这两个参数

##配置参数文件,主要在于"replication:、net:"这两部分(主、备库的参数文档是相同的)

[root@postgres bin]# cat /etc/mongod.conf 
# mongod.conf

# for documentation of all options, see:
#   http://docs.mongodb.org/manual/reference/configuration-options/

# where to write logging data.
systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log

# Where and how to store data.
storage:
  dbPath: /var/lib/mongo
  journal:
    enabled: true
#  engine:
#  wiredTiger:

# how the process runs
processManagement:
  timeZoneInfo: /usr/share/zoneinfo

# network interfaces
net:
  port: 27017
  bindIp: 0.0.0.0  # Enter 0.0.0.0,:: to bind to all IPv4 and IPv6 addresses or, alternatively, use the net.bindIpAll setting.


#security:

#operationProfiling:

replication:
  replSetName: rs0

#sharding:

## Enterprise-Only Options

#auditLog:

#snmp:

4.2、重新启动主、备节点的mongod服务,初始化集群信息

[root@postgres bin]#systemctl restart mongod

##通过 --replSet 和 --bind_ip 命令行选项指定副本集名称和 IP 绑定
# mongosh --port 28017 
# 初始化复制集
> rs.initiate({
    _id: "rs0",
    members: [{
        _id: 0,
        host: "192.168.10.101:28017"
    },{
        _id: 1,
        host: "192.168.10.101:28018"
    },{
        _id: 2,
        host: "192.168.10.101:28019"
    }]
})

rs0 [direct: primary] test> rs.conf()
{
  _id: 'rs0',
  version: 1,
  term: 1,
  members: [
    {
      _id: 0,
      host: '192.168.6.107:27017',
      arbiterOnly: false,
      buildIndexes: true,
      hidden: false,
      priority: 1,
      tags: {},
      secondaryDelaySecs: Long('0'),
      votes: 1
    },
    {
      _id: 1,
      host: '192.168.6.108:27017',
      arbiterOnly: false,
      buildIndexes: true,
      hidden: false,
      priority: 1,
      tags: {},
      secondaryDelaySecs: Long('0'),
      votes: 1
    },
    {
      _id: 2,
      host: '192.168.6.111:27017',
      arbiterOnly: false,
      buildIndexes: true,
      hidden: false,
      priority: 1,
      tags: {},
      secondaryDelaySecs: Long('0'),
      votes: 1
    }
  ],
  protocolVersion: Long('1'),
  writeConcernMajorityJournalDefault: true,
  settings: {
    chainingAllowed: true,
    heartbeatIntervalMillis: 2000,
    heartbeatTimeoutSecs: 10,
    electionTimeoutMillis: 10000,
    catchUpTimeoutMillis: -1,
    catchUpTakeoverDelayMillis: 30000,
    getLastErrorModes: {},
    getLastErrorDefaults: { w: 1, wtimeout: 0 },
    replicaSetId: ObjectId('669e1c9704a0c6a76d1844e7')
  }
}
rs0 [direct: primary] test> 

如果在这个地方报错

errmsg" : "This node was not started with the replSet option"

解决办法:

关闭sudo service mongod stop
查看状态sudo service mongod status
[root@postgres mongodb]# mongod --port=27001 --dbpath=./data/db --replSet=rs0
查看状态sudo service mongod status

4.3、如果查看主、备库之间的数据复制状态,故障测试

4.3.1、查看集群状态信息

从这里可以看出这是级联复制状态(部分信息):
107节点是主节点,108节点oplog(操作日志)来源与107节点,111节点oplog来源于108节点。

members: [
    {
      _id: 0,
      name: '192.168.6.107:27017',
      health: 1,
      state: 1,
      stateStr: 'PRIMARY',
      uptime: 11728,
      optime: { ts: Timestamp({ t: 1721713392, i: 1 }), t: Long('3') },
      optimeDate: ISODate('2024-07-23T05:43:12.000Z'),
      lastAppliedWallTime: ISODate('2024-07-23T05:43:12.038Z'),
      lastDurableWallTime: ISODate('2024-07-23T05:43:12.038Z'),
      syncSourceHost: '',
      syncSourceId: -1,
      infoMessage: '',
      electionTime: Timestamp({ t: 1721701683, i: 1 }),
      electionDate: ISODate('2024-07-23T02:28:03.000Z'),
      configVersion: 1,
      configTerm: 3,
      self: true,
      lastHeartbeatMessage: ''
    },
    {
      _id: 1,
      name: '192.168.6.108:27017',
      health: 1,
      state: 2,
      stateStr: 'SECONDARY',
      uptime: 11723,
      optime: { ts: Timestamp({ t: 1721713392, i: 1 }), t: Long('3') },
      optimeDurable: { ts: Timestamp({ t: 1721713392, i: 1 }), t: Long('3') },
      optimeDate: ISODate('2024-07-23T05:43:12.000Z'),
      optimeDurableDate: ISODate('2024-07-23T05:43:12.000Z'),
      lastAppliedWallTime: ISODate('2024-07-23T05:43:12.038Z'),
      lastDurableWallTime: ISODate('2024-07-23T05:43:12.038Z'),
      lastHeartbeat: ISODate('2024-07-23T05:43:16.407Z'),
      lastHeartbeatRecv: ISODate('2024-07-23T05:43:17.275Z'),
      pingMs: Long('0'),
      lastHeartbeatMessage: '',
      syncSourceHost: '192.168.6.107:27017',
      syncSourceId: 0,
      infoMessage: '',
      configVersion: 1,
      configTerm: 3
    },
    {
      _id: 2,
      name: '192.168.6.111:27017',
      health: 1,
      state: 2,
      stateStr: 'SECONDARY',
      uptime: 11708,
      optime: { ts: Timestamp({ t: 1721713392, i: 1 }), t: Long('3') },
      optimeDurable: { ts: Timestamp({ t: 1721713392, i: 1 }), t: Long('3') },
      optimeDate: ISODate('2024-07-23T05:43:12.000Z'),
      optimeDurableDate: ISODate('2024-07-23T05:43:12.000Z'),
      lastAppliedWallTime: ISODate('2024-07-23T05:43:12.038Z'),
      lastDurableWallTime: ISODate('2024-07-23T05:43:12.038Z'),
      lastHeartbeat: ISODate('2024-07-23T05:43:16.407Z'),
      lastHeartbeatRecv: ISODate('2024-07-23T05:43:17.274Z'),
      pingMs: Long('0'),
      lastHeartbeatMessage: '',
      syncSourceHost: '192.168.6.108:27017',
      syncSourceId: 1,
      infoMessage: '',
      configVersion: 1,
      configTerm: 3
    }
  ],
  ok: 1,

完整信息,如下所示:

[root@postgres ~]# mongosh
Current Mongosh Log ID: 669f42de9957bb839b482f8a
Connecting to:          mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+2.2.12
Using MongoDB:          6.0.16
Using Mongosh:          2.2.12

For mongosh info see: https://docs.mongodb.com/mongodb-shell/

------
   The server generated these startup warnings when booting
   2024-07-23T10:27:52.339+08:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
   2024-07-23T10:27:52.339+08:00: /sys/kernel/mm/transparent_hugepage/enabled is 'always'. We suggest setting it to 'never' in this binary version
   2024-07-23T10:27:52.339+08:00: /sys/kernel/mm/transparent_hugepage/defrag is 'always'. We suggest setting it to 'never' in this binary version
   2024-07-23T10:27:52.339+08:00: vm.max_map_count is too low
------


Deprecation warnings:
  - Using mongosh on the current operating system is deprecated, and support may be removed in a future release.
See https://www.mongodb.com/docs/mongodb-shell/install/#supported-operating-systems for documentation on supported platforms.
rs0 [direct: primary] test> rs.status();
{
  set: 'rs0',
  date: ISODate('2024-07-23T05:43:18.273Z'),
  myState: 1,
  term: Long('3'),
  syncSourceHost: '',
  syncSourceId: -1,
  heartbeatIntervalMillis: Long('2000'),
  majorityVoteCount: 2,
  writeMajorityCount: 2,
  votingMembersCount: 3,
  writableVotingMembersCount: 3,
  optimes: {
    lastCommittedOpTime: { ts: Timestamp({ t: 1721713392, i: 1 }), t: Long('3') },
    lastCommittedWallTime: ISODate('2024-07-23T05:43:12.038Z'),
    readConcernMajorityOpTime: { ts: Timestamp({ t: 1721713392, i: 1 }), t: Long('3') },
    appliedOpTime: { ts: Timestamp({ t: 1721713392, i: 1 }), t: Long('3') },
    durableOpTime: { ts: Timestamp({ t: 1721713392, i: 1 }), t: Long('3') },
    lastAppliedWallTime: ISODate('2024-07-23T05:43:12.038Z'),
    lastDurableWallTime: ISODate('2024-07-23T05:43:12.038Z')
  },
  lastStableRecoveryTimestamp: Timestamp({ t: 1721713392, i: 1 }),
  electionCandidateMetrics: {
    lastElectionReason: 'electionTimeout',
    lastElectionDate: ISODate('2024-07-23T02:28:03.652Z'),
    electionTerm: Long('3'),
    lastCommittedOpTimeAtElection: { ts: Timestamp({ t: 0, i: 0 }), t: Long('-1') },
    lastSeenOpTimeAtElection: { ts: Timestamp({ t: 1721651376, i: 1 }), t: Long('2') },
    numVotesNeeded: 2,
    priorityAtElection: 1,
    electionTimeoutMillis: Long('10000'),
    numCatchUpOps: Long('0'),
    newTermStartDate: ISODate('2024-07-23T02:28:05.466Z'),
    wMajorityWriteAvailabilityDate: ISODate('2024-07-23T02:28:05.745Z')
  },
  members: [
    {
      _id: 0,
      name: '192.168.6.107:27017',
      health: 1,
      state: 1,
      stateStr: 'PRIMARY',
      uptime: 11728,
      optime: { ts: Timestamp({ t: 1721713392, i: 1 }), t: Long('3') },
      optimeDate: ISODate('2024-07-23T05:43:12.000Z'),
      lastAppliedWallTime: ISODate('2024-07-23T05:43:12.038Z'),
      lastDurableWallTime: ISODate('2024-07-23T05:43:12.038Z'),
      syncSourceHost: '',
      syncSourceId: -1,
      infoMessage: '',
      electionTime: Timestamp({ t: 1721701683, i: 1 }),
      electionDate: ISODate('2024-07-23T02:28:03.000Z'),
      configVersion: 1,
      configTerm: 3,
      self: true,
      lastHeartbeatMessage: ''
    },
    {
      _id: 1,
      name: '192.168.6.108:27017',
      health: 1,
      state: 2,
      stateStr: 'SECONDARY',
      uptime: 11723,
      optime: { ts: Timestamp({ t: 1721713392, i: 1 }), t: Long('3') },
      optimeDurable: { ts: Timestamp({ t: 1721713392, i: 1 }), t: Long('3') },
      optimeDate: ISODate('2024-07-23T05:43:12.000Z'),
      optimeDurableDate: ISODate('2024-07-23T05:43:12.000Z'),
      lastAppliedWallTime: ISODate('2024-07-23T05:43:12.038Z'),
      lastDurableWallTime: ISODate('2024-07-23T05:43:12.038Z'),
      lastHeartbeat: ISODate('2024-07-23T05:43:16.407Z'),
      lastHeartbeatRecv: ISODate('2024-07-23T05:43:17.275Z'),
      pingMs: Long('0'),
      lastHeartbeatMessage: '',
      syncSourceHost: '192.168.6.107:27017',
      syncSourceId: 0,
      infoMessage: '',
      configVersion: 1,
      configTerm: 3
    },
    {
      _id: 2,
      name: '192.168.6.111:27017',
      health: 1,
      state: 2,
      stateStr: 'SECONDARY',
      uptime: 11708,
      optime: { ts: Timestamp({ t: 1721713392, i: 1 }), t: Long('3') },
      optimeDurable: { ts: Timestamp({ t: 1721713392, i: 1 }), t: Long('3') },
      optimeDate: ISODate('2024-07-23T05:43:12.000Z'),
      optimeDurableDate: ISODate('2024-07-23T05:43:12.000Z'),
      lastAppliedWallTime: ISODate('2024-07-23T05:43:12.038Z'),
      lastDurableWallTime: ISODate('2024-07-23T05:43:12.038Z'),
      lastHeartbeat: ISODate('2024-07-23T05:43:16.407Z'),
      lastHeartbeatRecv: ISODate('2024-07-23T05:43:17.274Z'),
      pingMs: Long('0'),
      lastHeartbeatMessage: '',
      syncSourceHost: '192.168.6.108:27017',
      syncSourceId: 1,
      infoMessage: '',
      configVersion: 1,
      configTerm: 3
    }
  ],
  ok: 1,
  '$clusterTime': {
    clusterTime: Timestamp({ t: 1721713392, i: 1 }),
    signature: {
      hash: Binary.createFromBase64('AAAAAAAAAAAAAAAAAAAAAAAAAAA=', 0),
      keyId: Long('0')
    }
  },
  operationTime: Timestamp({ t: 1721713392, i: 1 })
}
rs0 [direct: primary] test> 

如果此时我们宕掉108节点

[root@postgres ~]# systemctl status mongod
● mongod.service - MongoDB Database Server
   Loaded: loaded (/usr/lib/systemd/system/mongod.service; enabled; vendor preset: disabled)
   Active: active (running) since Tue 2024-07-23 10:27:51 CST; 3h 27min ago
     Docs: https://docs.mongodb.org/manual
 Main PID: 1349 (mongod)
    Tasks: 74
   CGroup: /system.slice/mongod.service
           └─1349 /usr/bin/mongod -f /etc/mongod.conf

Jul 23 10:27:51 postgres systemd[1]: Started MongoDB Database Server.
Jul 23 10:27:52 postgres mongod[1349]: {"t":{"$date":"2024-07-23T02:27:52.351Z"},"s":"I",  "c":"CONTROL",  "id":7484500, "ctx":"-","msg":"Environment varia...to false"}
Hint: Some lines were ellipsized, use -l to show in full.
[root@postgres ~]# systemctl stop mongod
[root@postgres ~]# systemctl status mongod
● mongod.service - MongoDB Database Server
   Loaded: loaded (/usr/lib/systemd/system/mongod.service; enabled; vendor preset: disabled)
   Active: inactive (dead) since Tue 2024-07-23 13:55:20 CST; 1s ago
     Docs: https://docs.mongodb.org/manual
  Process: 1349 ExecStart=/usr/bin/mongod $OPTIONS (code=exited, status=0/SUCCESS)
 Main PID: 1349 (code=exited, status=0/SUCCESS)

Jul 23 10:27:51 postgres systemd[1]: Started MongoDB Database Server.
Jul 23 10:27:52 postgres mongod[1349]: {"t":{"$date":"2024-07-23T02:27:52.351Z"},"s":"I",  "c":"CONTROL",  "id":7484500, "ctx":"-","msg":"Environment varia...to false"}
Jul 23 13:55:04 postgres systemd[1]: Stopping MongoDB Database Server...
Jul 23 13:55:20 postgres systemd[1]: Stopped MongoDB Database Server.
Hint: Some lines were ellipsized, use -l to show in full.
[root@postgres ~]# 

查看107节点的集群状态信息,我们可以看到:

111节点的oplog日志来源就指向107节点了(部分信息)

 members: [
    {
      _id: 0,
      name: '192.168.6.107:27017',
      health: 1,
      state: 1,
      stateStr: 'PRIMARY',
      uptime: 12562,
      optime: { ts: Timestamp({ t: 1721714232, i: 1 }), t: Long('3') },
      optimeDate: ISODate('2024-07-23T05:57:12.000Z'),
      lastAppliedWallTime: ISODate('2024-07-23T05:57:12.113Z'),
      lastDurableWallTime: ISODate('2024-07-23T05:57:12.113Z'),
      syncSourceHost: '',
      syncSourceId: -1,
      infoMessage: '',
      electionTime: Timestamp({ t: 1721701683, i: 1 }),
      electionDate: ISODate('2024-07-23T02:28:03.000Z'),
      configVersion: 1,
      configTerm: 3,
      self: true,
      lastHeartbeatMessage: ''
    },
    {
      _id: 1,
      name: '192.168.6.108:27017',
      health: 0,
      state: 8,
      stateStr: '(not reachable/healthy)',
      uptime: 0,
      optime: { ts: Timestamp({ t: 0, i: 0 }), t: Long('-1') },
      optimeDurable: { ts: Timestamp({ t: 0, i: 0 }), t: Long('-1') },
      optimeDate: ISODate('1970-01-01T00:00:00.000Z'),
      optimeDurableDate: ISODate('1970-01-01T00:00:00.000Z'),
      lastAppliedWallTime: ISODate('2024-07-23T05:55:12.103Z'),
      lastDurableWallTime: ISODate('2024-07-23T05:55:12.103Z'),
      lastHeartbeat: ISODate('2024-07-23T05:57:11.049Z'),
      lastHeartbeatRecv: ISODate('2024-07-23T05:55:19.720Z'),
      pingMs: Long('0'),
      lastHeartbeatMessage: 'Error connecting to 192.168.6.108:27017 :: caused by :: Connection refused',
      syncSourceHost: '',
      syncSourceId: -1,
      infoMessage: '',
      configVersion: 1,
      configTerm: 3
    },
    {
      _id: 2,
      name: '192.168.6.111:27017',
      health: 1,
      state: 2,
      stateStr: 'SECONDARY',
      uptime: 12542,
      optime: { ts: Timestamp({ t: 1721714222, i: 1 }), t: Long('3') },
      optimeDurable: { ts: Timestamp({ t: 1721714222, i: 1 }), t: Long('3') },
      optimeDate: ISODate('2024-07-23T05:57:02.000Z'),
      optimeDurableDate: ISODate('2024-07-23T05:57:02.000Z'),
      lastAppliedWallTime: ISODate('2024-07-23T05:57:12.113Z'),
      lastDurableWallTime: ISODate('2024-07-23T05:57:12.113Z'),
      lastHeartbeat: ISODate('2024-07-23T05:57:11.004Z'),
      lastHeartbeatRecv: ISODate('2024-07-23T05:57:11.216Z'),
      pingMs: Long('0'),
      lastHeartbeatMessage: '',
      syncSourceHost: '192.168.6.107:27017',
      syncSourceId: 0,
      infoMessage: '',
      configVersion: 1,
      configTerm: 3
    }
  ],

然后启动108节点mongod服务,查看集群状态

这时候的108节点已经加入到集群中了,此时集群状态是级联复制

 members: [
    {
      _id: 0,
      name: '192.168.6.107:27017',
      health: 1,
      state: 1,
      stateStr: 'PRIMARY',
      uptime: 12817,
      optime: { ts: Timestamp({ t: 1721714482, i: 1 }), t: Long('3') },
      optimeDate: ISODate('2024-07-23T06:01:22.000Z'),
      lastAppliedWallTime: ISODate('2024-07-23T06:01:22.136Z'),
      lastDurableWallTime: ISODate('2024-07-23T06:01:22.136Z'),
      syncSourceHost: '',
      syncSourceId: -1,
      infoMessage: '',
      electionTime: Timestamp({ t: 1721701683, i: 1 }),
      electionDate: ISODate('2024-07-23T02:28:03.000Z'),
      configVersion: 1,
      configTerm: 3,
      self: true,
      lastHeartbeatMessage: ''
    },
    {
      _id: 1,
      name: '192.168.6.108:27017',
      health: 1,
      state: 2,
      stateStr: 'SECONDARY',
      uptime: 17,
      optime: { ts: Timestamp({ t: 1721714482, i: 1 }), t: Long('3') },
      optimeDurable: { ts: Timestamp({ t: 1721714482, i: 1 }), t: Long('3') },
      optimeDate: ISODate('2024-07-23T06:01:22.000Z'),
      optimeDurableDate: ISODate('2024-07-23T06:01:22.000Z'),
      lastAppliedWallTime: ISODate('2024-07-23T06:01:22.136Z'),
      lastDurableWallTime: ISODate('2024-07-23T06:01:22.136Z'),
      lastHeartbeat: ISODate('2024-07-23T06:01:25.327Z'),
      lastHeartbeatRecv: ISODate('2024-07-23T06:01:26.625Z'),
      pingMs: Long('0'),
      lastHeartbeatMessage: '',
      syncSourceHost: '192.168.6.111:27017',
      syncSourceId: 2,
      infoMessage: '',
      configVersion: 1,
      configTerm: 3
    },
    {
      _id: 2,
      name: '192.168.6.111:27017',
      health: 1,
      state: 2,
      stateStr: 'SECONDARY',
      uptime: 12797,
      optime: { ts: Timestamp({ t: 1721714482, i: 1 }), t: Long('3') },
      optimeDurable: { ts: Timestamp({ t: 1721714482, i: 1 }), t: Long('3') },
      optimeDate: ISODate('2024-07-23T06:01:22.000Z'),
      optimeDurableDate: ISODate('2024-07-23T06:01:22.000Z'),
      lastAppliedWallTime: ISODate('2024-07-23T06:01:22.136Z'),
      lastDurableWallTime: ISODate('2024-07-23T06:01:22.136Z'),
      lastHeartbeat: ISODate('2024-07-23T06:01:25.168Z'),
      lastHeartbeatRecv: ISODate('2024-07-23T06:01:25.398Z'),
      pingMs: Long('0'),
      lastHeartbeatMessage: '',
      syncSourceHost: '192.168.6.107:27017',
      syncSourceId: 0,
      infoMessage: '',
      configVersion: 1,
      configTerm: 3
    }
  ],

五、使用docker安装三节点的MongoDB集群

5.1、安装环境介绍

服务器IPOS登录信息节点状态、部署服务及对应端口号
192.168.6.117mongod/mongod容器内Mongo主(27017),宿主机映射端口(28017)
192.168.6.117mongod/mongod容器内Mongo备(27017),宿主机映射端口(28018)
192.168.6.117mongod/mongod容器内Mongo备(27017),宿主机映射端口(28019)

使用外挂式部署,把数据库的日志目录,数据目录,参数配置文件给挂载到容器

创建数据目录:
mkdir -p /data/db{1,2,3}/logs

创建日志目录:
mkdir -p /data/db{1,2,3}/logs

创建配置文件/data/db1/mongod.conf,内容如下:
systemLog:
  destination: file
  path: /data/logs/mongod.log # log path
  logAppend: true
storage:   
  dbPath: /data/db # data directory      
net:
  bindIp: 0.0.0.0
  port: 27017 # port
replication:
  replSetName: rs0 # 复制集名称
security:
  authorization: disabled
  #将该配置文件复制到db2、db3 对应的目录下,注意其中配置的是容器中的地址,而不是宿主机对应的地址 

5.2、先保证docker可以获得镜像

[root@bogon ~]# docker images
REPOSITORY   TAG       IMAGE ID       CREATED       SIZE
mongo        latest    dfda7a2cf273   2 years ago   693MB
[root@bogon ~]# 

5.3、创建容器服务

root@bogon db1]# docker run --name mongodb1 -d -v /data/db1:/data/db -v /data/db1/logs:/data/logs -v /data/db1/mongod.conf:/data/conf/mongod.conf -p 28017:27017 mongo --replSet rs0
6b515f49051bd9b2d5dfe8bc2b1d5585db10700616f89a0c3fc9b4d0fa8be517
[root@bogon db1]# docker run --name mongodb2 -d -v /data/db2:/data/db -v /data/db2/logs:/data/logs -v /data/db2/mongod.conf:/data/conf/mongod.conf -p 28018:27017 mongo --replSet rs0
3fc1d7d55b7c3336134e733667077f6cdb7f72fa5f692ccc5e8bae7404b79a3a
[root@bogon db1]# docker run --name mongodb3 -d -v /data/db3:/data/db -v /data/db3/logs:/data/logs -v /data/db3/mongod.conf:/data/conf/mongod.conf -p 28019:27017 mongo --replSet rs0
6e68413a18f1c5dc622fe642ed7f10fd772f6d35199446d6da40e85104c96719
[root@bogon db1]# docker ps -a
CONTAINER ID   IMAGE     COMMAND                  CREATED       STATUS       PORTS                                           NAMES
6e68413a18f1   mongo     "docker-entrypoint.s…"   2 hours ago   Up 2 hours   0.0.0.0:28019->27017/tcp, :::28019->27017/tcp   mongodb3
3fc1d7d55b7c   mongo     "docker-entrypoint.s…"   2 hours ago   Up 2 hours   0.0.0.0:28018->27017/tcp, :::28018->27017/tcp   mongodb2
6b515f49051b   mongo     "docker-entrypoint.s…"   2 hours ago   Up 2 hours   0.0.0.0:28017->27017/tcp, :::28017->27017/tcp   mongodb1
[root@bogon db1]# 
–name:指定容器名称
-d:后台运行
-v:将宿主机文件挂载到容器中,注意格式为:“宿主机路径 : 容器路径”
-p:绑定宿主机和容器的端口,注意格式为:“宿主机端口 : 容器端口”
--replSet 命令行选项指定副本集名称

注意:如果在这个步骤程序报错

docker: Error response from daemon: failed to create task for container: failed to create shim task

解决办法:
那就去把虚拟机的cup核心数给到4个,如下所示CPUs: 4

[root@bogon db1]# docker info
Client: Docker Engine - Community
 Version:    26.1.4
 Context:    default
 Debug Mode: false
 Plugins:
  buildx: Docker Buildx (Docker Inc.)
    Version:  v0.14.1
    Path:     /usr/libexec/docker/cli-plugins/docker-buildx
  compose: Docker Compose (Docker Inc.)
    Version:  v2.27.1
    Path:     /usr/libexec/docker/cli-plugins/docker-compose

Server:
 Containers: 3
  Running: 3
  Paused: 0
  Stopped: 0
 Images: 1
 Server Version: 26.1.4
 Storage Driver: overlay2
  Backing Filesystem: xfs
  Supports d_type: true
  Using metacopy: false
  Native Overlay Diff: true
  userxattr: false
 Logging Driver: json-file
 Cgroup Driver: cgroupfs
 Cgroup Version: 1
 Plugins:
  Volume: local
  Network: bridge host ipvlan macvlan null overlay
  Log: awslogs fluentd gcplogs gelf journald json-file local splunk syslog
 Swarm: inactive
 Runtimes: io.containerd.runc.v2 runc
 Default Runtime: runc
 Init Binary: docker-init
 containerd version: d2d58213f83a351ca8f528a95fbd145f5654e957
 runc version: v1.1.12-0-g51d5e94
 init version: de40ad0
 Security Options:
  seccomp
   Profile: builtin
 Kernel Version: 3.10.0-1160.el7.x86_64
 Operating System: CentOS Linux 7 (Core)
 OSType: linux
 Architecture: x86_64
 CPUs: 4
 Total Memory: 3.682GiB
 Name: bogon
 ID: 4755b2d0-6df8-401e-afce-56879b2db168
 Docker Root Dir: /var/lib/docker
 Debug Mode: false
 Experimental: false
 Insecure Registries:
  127.0.0.0/8
 Registry Mirrors:
  https://g0q805gt.mirror.aliyuncs.com/
 Live Restore Enabled: false
[root@bogon db1]# 

查看端口号:

[root@bogon ~]# netstat -tunlp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
tcp        0      0 0.0.0.0:111             0.0.0.0:*               LISTEN      753/rpcbind         
tcp        0      0 0.0.0.0:28017           0.0.0.0:*               LISTEN      13311/docker-proxy  
tcp        0      0 0.0.0.0:28018           0.0.0.0:*               LISTEN      13468/docker-proxy  
tcp        0      0 0.0.0.0:28019           0.0.0.0:*               LISTEN      13626/docker-proxy  
tcp        0      0 192.168.122.1:53        0.0.0.0:*               LISTEN      1746/dnsmasq     

5.4、初始化集群信息

[root@bogon db1]# docker exec -it mongodb1 bash
root@6b515f49051b:/# cd /data
root@6b515f49051b:/data# ls
conf  configdb  db  logs
root@6b515f49051b:/data# cd conf
root@6b515f49051b:/data/conf# ls
mongod.conf
root@6b515f49051b:/data/conf# cat mongod.conf 
systemLog:
  destination: file
  path: /data/logs/mongod.log
  logAppend: true
storage:
  dbPath: /data/db
net:
  bindIp: 0.0.0.0
  port: 27017
replication:
  replSetName: rs0
security:
  authorization: disabled
root@6b515f49051b:/data/conf# mongosh --host 192.168.6.117 -p 28017
Current Mongosh Log ID: 669f925d7e018336f6fd24ed
Connecting to:          mongodb://192.168.6.117:27017/?directConnection=true
MongoParseError: credentials must be an object with 'username' and 'password' properties
root@6b515f49051b:/data/conf# mongosh --host 192.168.6.117 --port 28017
Current Mongosh Log ID: 669f92691df6dc4990d8bc6b
Connecting to:          mongodb://192.168.6.117:28017/?directConnection=true
Using MongoDB:          5.0.5
Using Mongosh:          1.1.6

For mongosh info see: https://docs.mongodb.com/mongodb-shell/


To help improve our products, anonymous usage data is collected and sent to MongoDB periodically (https://www.mongodb.com/legal/privacy-policy).
You can opt-out by running the disableTelemetry() command.

------
   The server generated these startup warnings when booting:
   2024-07-23T11:18:51.750+00:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
   2024-07-23T11:18:51.750+00:00: /sys/kernel/mm/transparent_hugepage/enabled is 'always'. We suggest setting it to 'never'
   2024-07-23T11:18:51.750+00:00: /sys/kernel/mm/transparent_hugepage/defrag is 'always'. We suggest setting it to 'never'
------

test> rs.initiate( {
Browserslist: caniuse-lite is outdated. Please run:
npx browserslist@latest --update-db

Why you should do it regularly:
https://github.com/browserslist/browserslist#browsers-data-updating
...    _id : "rs0",
...    members: [
...       { _id: 0, host: "192.168.6.117:28017" },
...       { _id: 1, host: "192.168.6.117:28018" },
...       { _id: 2, host: "192.168.6.117:28019" }
...    ]
... })
Browserslist: caniuse-lite is outdated. Please run:
  npx browserslist@latest --update-db
  Why you should do it regularly: https://github.com/browserslist/browserslist#browsers-data-updating
{ ok: 1 }
rs0 [direct: other] test> 

查看集群配置信息


rs0 [direct: other] test> rs.conf()
{
  _id: 'rs0',
  version: 1,
  term: 1,
  members: [
    {
      _id: 0,
      host: '192.168.6.117:28017',
      arbiterOnly: false,
      buildIndexes: true,
      hidden: false,
      priority: 1,
      tags: {},
      secondaryDelaySecs: Long("0"),
      votes: 1
    },
    {
      _id: 1,
      host: '192.168.6.117:28018',
      arbiterOnly: false,
      buildIndexes: true,
      hidden: false,
      priority: 1,
      tags: {},
      secondaryDelaySecs: Long("0"),
      votes: 1
    },
    {
      _id: 2,
      host: '192.168.6.117:28019',
      arbiterOnly: false,
      buildIndexes: true,
      hidden: false,
      priority: 1,
      tags: {},
      secondaryDelaySecs: Long("0"),
      votes: 1
    }
  ],
  protocolVersion: Long("1"),
  writeConcernMajorityJournalDefault: true,
  settings: {
    chainingAllowed: true,
    heartbeatIntervalMillis: 2000,
    heartbeatTimeoutSecs: 10,
    electionTimeoutMillis: 10000,
    catchUpTimeoutMillis: -1,
    catchUpTakeoverDelayMillis: 30000,
    getLastErrorModes: {},
    getLastErrorDefaults: { w: 1, wtimeout: 0 },
    replicaSetId: ObjectId("669f928167076c3e3b16b5e4")
  }
}
rs0 [direct: primary] test> rs.status()
{
  set: 'rs0',
  date: ISODate("2024-07-23T11:23:22.473Z"),
  myState: 1,
  term: Long("1"),
  syncSourceHost: '',
  syncSourceId: -1,
  heartbeatIntervalMillis: Long("2000"),
  majorityVoteCount: 2,
  writeMajorityCount: 2,
  votingMembersCount: 3,
  writableVotingMembersCount: 3,
  optimes: {
    lastCommittedOpTime: { ts: Timestamp({ t: 1721733802, i: 1 }), t: Long("1") },
    lastCommittedWallTime: ISODate("2024-07-23T11:23:22.321Z"),
    readConcernMajorityOpTime: { ts: Timestamp({ t: 1721733802, i: 1 }), t: Long("1") },
    appliedOpTime: { ts: Timestamp({ t: 1721733802, i: 1 }), t: Long("1") },
    durableOpTime: { ts: Timestamp({ t: 1721733802, i: 1 }), t: Long("1") },
    lastAppliedWallTime: ISODate("2024-07-23T11:23:22.321Z"),
    lastDurableWallTime: ISODate("2024-07-23T11:23:22.321Z")
  },
  lastStableRecoveryTimestamp: Timestamp({ t: 1721733761, i: 1 }),
  electionCandidateMetrics: {
    lastElectionReason: 'electionTimeout',
    lastElectionDate: ISODate("2024-07-23T11:22:52.288Z"),
    electionTerm: Long("1"),
    lastCommittedOpTimeAtElection: { ts: Timestamp({ t: 1721733761, i: 1 }), t: Long("-1") },
    lastSeenOpTimeAtElection: { ts: Timestamp({ t: 1721733761, i: 1 }), t: Long("-1") },
    numVotesNeeded: 2,
    priorityAtElection: 1,
    electionTimeoutMillis: Long("10000"),
    numCatchUpOps: Long("0"),
    newTermStartDate: ISODate("2024-07-23T11:22:52.309Z"),
    wMajorityWriteAvailabilityDate: ISODate("2024-07-23T11:22:53.055Z")
  },
  members: [
    {
      _id: 0,
      name: '192.168.6.117:28017',
      health: 1,
      state: 1,
      stateStr: 'PRIMARY',
      uptime: 271,
      optime: { ts: Timestamp({ t: 1721733802, i: 1 }), t: Long("1") },
      optimeDate: ISODate("2024-07-23T11:23:22.000Z"),
      lastAppliedWallTime: ISODate("2024-07-23T11:23:22.321Z"),
      lastDurableWallTime: ISODate("2024-07-23T11:23:22.321Z"),
      syncSourceHost: '',
      syncSourceId: -1,
      infoMessage: '',
      electionTime: Timestamp({ t: 1721733772, i: 1 }),
      electionDate: ISODate("2024-07-23T11:22:52.000Z"),
      configVersion: 1,
      configTerm: 1,
      self: true,
      lastHeartbeatMessage: ''
    },
    {
      _id: 1,
      name: '192.168.6.117:28018',
      health: 1,
      state: 2,
      stateStr: 'SECONDARY',
      uptime: 41,
      optime: { ts: Timestamp({ t: 1721733802, i: 1 }), t: Long("1") },
      optimeDurable: { ts: Timestamp({ t: 1721733802, i: 1 }), t: Long("1") },
      optimeDate: ISODate("2024-07-23T11:23:22.000Z"),
      optimeDurableDate: ISODate("2024-07-23T11:23:22.000Z"),
      lastAppliedWallTime: ISODate("2024-07-23T11:23:22.321Z"),
      lastDurableWallTime: ISODate("2024-07-23T11:23:22.321Z"),
      lastHeartbeat: ISODate("2024-07-23T11:23:22.326Z"),
      lastHeartbeatRecv: ISODate("2024-07-23T11:23:21.337Z"),
      pingMs: Long("0"),
      lastHeartbeatMessage: '',
      syncSourceHost: '192.168.6.117:28017',
      syncSourceId: 0,
      infoMessage: '',
      configVersion: 1,
      configTerm: 1
    },
    {
      _id: 2,
      name: '192.168.6.117:28019',
      health: 1,
      state: 2,
      stateStr: 'SECONDARY',
      uptime: 41,
      optime: { ts: Timestamp({ t: 1721733802, i: 1 }), t: Long("1") },
      optimeDurable: { ts: Timestamp({ t: 1721733802, i: 1 }), t: Long("1") },
      optimeDate: ISODate("2024-07-23T11:23:22.000Z"),
      optimeDurableDate: ISODate("2024-07-23T11:23:22.000Z"),
      lastAppliedWallTime: ISODate("2024-07-23T11:23:22.321Z"),
      lastDurableWallTime: ISODate("2024-07-23T11:23:22.321Z"),
      lastHeartbeat: ISODate("2024-07-23T11:23:22.326Z"),
      lastHeartbeatRecv: ISODate("2024-07-23T11:23:21.337Z"),
      pingMs: Long("0"),
      lastHeartbeatMessage: '',
      syncSourceHost: '192.168.6.117:28017',
      syncSourceId: 0,
      infoMessage: '',
      configVersion: 1,
      configTerm: 1
    }
  ],
  ok: 1,
  '$clusterTime': {
    clusterTime: Timestamp({ t: 1721733802, i: 1 }),
    signature: {
      hash: Binary(Buffer.from("0000000000000000000000000000000000000000", "hex"), 0),
      keyId: Long("0")
    }
  },
  operationTime: Timestamp({ t: 1721733802, i: 1 })
}
rs0 [direct: primary] test> 

5.5、使用图形化工具连接主节点

在这里插入图片描述

Mongos 复制集常用命令:

命令描述
rs.add()为复制集新增节点
rs.addArb()为复制集新增一个 arbiter
rs.conf()返回复制集配置信息
rs.freeze()防止当前节点在一段时间内选举成为主节点
rs.help()返回 replica set 的命令帮助
rs.initiate()初始化一个新的复制集
rs.printReplicationInfo()以主节点的视角返回复制的状态报告
rs.printSecondaryReplicationInfo()以从节点的视角返回复制状态报告
rs.reconfig()通过重新应用复制集配置来为复制集更新配置
rs.remove()从复制集中移除一个节点
rs.secondaryOk()为当前的连接设置从节点可读
db.getMongo().setReadPref(“secondary”)为当前的连接设置从节点可读,推荐使用
rs.status()返回复制集状态信息
rs.stepDown()让当前的 primary 变为从节点并触发 election
rs.syncFrom()设置复制集节点从哪个节点处同步数据,将会覆盖默认选取逻辑
  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要离线安装MongoDB数据库集群,你需要下载并安装MongoDB主程序和Mongosh命令行操作工具。首先,你可以从提供的下载链接中下载MongoDB主程序的压缩包[mongodb-linux-x86_64-rhel70-6.0.1.tgz]。解压缩该文件后,你可以按照MongoDB安装指南进行进一步的安装步骤。 同时,你还需要下载Mongosh命令行操作工具的rpm包[mongodb-mongosh-shared-openssl1-1.6.0.x86_64.rpm]。这个工具是在MongoDB 6版本中被独立剥离出来的,所以你需要单独安装它。下载完成后,你可以使用rpm命令进行安装安装完成后,你可以使用mongosh命令进入MongoDB数据库集群,并进行相关的操作。请注意,在离线安装时,你可能还需要手动配置一些依赖和环境变量,以确保MongoDB集群正常运行。 总结起来,mongodb数据库集群的离线安装步骤如下: 1. 下载MongoDB主程序压缩包[mongodb-linux-x86_64-rhel70-6.0.1.tgz]并解压缩。 2. 按照MongoDB安装指南进行进一步的安装步骤。 3. 下载Mongosh命令行操作工具的rpm包[mongodb-mongosh-shared-openssl1-1.6.0.x86_64.rpm]。 4. 使用rpm命令安装Mongosh工具。 5. 完成安装后,使用mongosh命令进入MongoDB数据库集群进行操作。 请注意,离线安装可能需要更多的配置和安装步骤,具体取决于你的操作系统和环境。建议在安装之前参考MongoDB的官方文档和安装指南,以确保正确安装和配置MongoDB数据库集群。 :下载地址:下载 :mongodb-mongosh-shared-openssl1-1.6.0.x86_64.rpm<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [MongoBd 离线安装与管理](https://blog.csdn.net/hnmpf/article/details/128114148)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值