MongoDB-4.4.2 stand-alone installation and replica set configuration

table of Contents

1 Single-machine installation of MongoDB-4.4.2

1.1 Download of software package

1.2 Install MongoDB-4.4.2

1.2.1 Unzip

1.2.2 Rename

1.2.3 Configure environment variables

1.3 Start MongoDB

1.3.1 Edit configuration file

1.3.3 Execute the following command to start MongoDB with the specified configuration

1.3.4 Local connection test

1.4 Close MongoDB

1.5 Set MongoDB to start in systemctl mode

2 MongoDB replica set deployment

2.1 Introduction to the replica set

2.2 Replica set configuration

2.2.1 Modify the configuration file

2.2.2 Start the node

2.2.3 Replica set initialization

2.2.4 Replica set update

2.2.5 View replica set status information

2.2.6 Test replica set

3 Turn on the security authentication of the database

3.1 Log in to the master node to create a super user

3.2 Create a key file for replica set authentication

3.3 Update MongoDB configuration file

3.4 Permission authentication of test replica set

Summary of database permissions


This tutorial is the installation and configuration on the basis of turning off the Linux server firewall. If you encounter a connection failure during the reference process, please check the firewall. Take CentOS7 as an example: systemctl status firewalld , the shutdown command is: systemctl stop firewalld , to prohibit self-starting after booting: systemctl disable firewalld

1 Single-machine installation of MongoDB-4.4.2

1.1 Download of software package

Download link: https://www.mongodb.com/try/download/community

Attached is the download link of MongoDB-4.4.2: https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-rhel70-4.4.2.tgz

Download directly on the server: wget https://fastdl.mongodb.org/linux/ mongodb-linux-x86_64-rhel70-4.4.2.tgz

1.2 Install MongoDB-4.4.2

1.2.1 Unzip

# 解压到当前文件tar -xzvf mongodb-linux-x86_64-rhel70-4.4.2.tgz # 解压到指定的文件tar -xzvf mongodb-linux-x86_64-rhel70-4.4.2.tgz -C /home

1.2.2 Rename

# 解压后的名字太长,这里我们重命名cd /homemv mongodb-linux-x86_64-rhel70-4.4.2 mongodb-4.4.2

1.2.3 Configure environment variables

# 配置环境变量,使MongoDB指令可以全局执行,下面使用两种方式进行设置,随意选择 # 方式一:在/usr/bin文件下(该文件夹可以繁殖后期安装的一些软件运行脚本)建立软连接ln -s /home/mongodb-4.4.2/bin/mongod /usr/bin/mongodln -s /home/mongodb-4.4.2/bin/mongo /usr/bin/mongo # 方式二:在 /etc/profile 配置文件的最后添加 MongoDB 环境变量vim /etc/profileexport PATH=$PATH:/home/mongodb-4.4.2/bin# 保存退出加载配置,使之生效source /etc/profile

1.3 Start MongoDB

1.3.1 Edit configuration file

Before editing the configuration file, create two folders data and log to store MongoDB data and log files respectively. Be sure to create it in advance! ! ! !

# 创建存储数据库的文件夹,这里根据服务器的硬盘分配情况自己规划mkdir -p /data/mongodb/data # 创建存储日志的文件夹mkdir -p /data/mongodb/log

Formally start writing configuration files

Define the storage location of the configuration file yourself, generally placed in the folder during installation

cd /home/ mongodb-4.4.2

vi mongodb.conf

Just copy the configuration file below, if the database is different from the log file, just modify it! !

port=27017 	#端口,MongoDB默认端口为27017,注意防火墙的设置dbpath= /data/mongodb/data 	 #数据库存文件存放目录logpath= /data/mongodb/logs/mongodb.log 	#日志文件存放路径logappend=true 	#使用追加的方式写日志fork=true 	#以守护进程的方式运行,创建服务器进程maxConns=1000 	#最大同时连接数# noauth=true 	#不启用验证,默认不启用验证,这里也可以不用写journal=true 	#每次写入会记录一条操作日志(通过journal可以重新构造出写入的数据)。bind_ip = 0.0.0.0  	#这样就可外部访问

1.3.3 Execute the following command to start MongoDB with the specified configuration

# 启动MongoDBmongod --config /home/mongodb-4.4.2/mongodb.conf # 或者mongod -f /home/mongodb-4.4.2/mongodb.conf

See the following results, indicating that the startup was successful

You can also view the process

1.3.4 Local connection test

Direct input: mongo

1.4 Close MongoDB

# 关闭服务器指令mongod --shutdown --dbpath /data/mongodb/data

1.5 Set MongoDB to start in systemctl mode

vi /usr/lib/systemd/system/mongodb.service

[Unit]Description=mongodbAfter=network.target remote-fs.target nss-lookup.target    [Service]  Type=forking# 根据自己的配置文件位置进行修改  ExecStart=/home/mongodb-4.4.2/bin/mongod --config /home/mongodb-4.4.2/mongodb.confExecReload=/bin/kill -s HUP $MAINPID# 根据自己的配置文件位置进行修改 ExecStop=/home/mongodb-4.4.2/bin/mongod --shutdown --config /home/mongodb-4.4.2/mongodb.confPrivateTmp=true      [Install]  WantedBy=multi-user.target

Reload systemctl: systemctl daemon-reload

After the setting is complete, you can use systemctl to start: systemctl start mongodb

So far, the single-machine installation of MongoDB has been introduced. The method of adding authentication will be introduced in a unified manner later.

MongoDB configuration file interpretation: refer to https://blog.csdn.net/ningjiebing/article/details/90607803?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522162253367016780262587400%2522%252C%2522scm%2522%253A%252220140713.130102334 ..%2522%257D&request_id=162253367016780262587400&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduend~default-2-90607803.first_rank_v2_pc_rank_v29&utm_term=mongodb%E6E7%85% 8D%E6 %96%87%E4%BB%B6&spm=1018.2226.3001.4187

# 数据文件位置dbpath = /opt/module/mongoData# 日志文件位置logpath = /opt/module/mongoLog/mongodb.log# 以追加方式写入日志,true为追加。false是覆盖logappend = true# 日志输出都发送到主机的syslog系统,而不是标准输出到logpath指定日志文件。syslog和logpath不能一起用,会报错:Cant use both a logpath and syslog# syslog = true# 绑定地址。默认127.0.0.1,只能通过本地连接。进程绑定和监听来自这个地址上的应用连接。要是需要给其他服务器连接,则需要注释掉这个或则 把IP改成本机地址,# 如192.168.200.201[其他服务器用 mongo --host=192.168.200.201 连接] ,可以用一个逗号分隔的列表绑定多个IP地址。# 远程访问则配置为0.0.0.0# bind_ip = 127.0.0.1# 默认端口27017port = 27017# 是否后台运行,设置为true 启动 进程在后台运行的守护进程模式。默认false。fork = true# 安静模式。这个选项可以过滤掉一些无用的日志信息,若需要调试使用请设置为falsequiet = false# 启用日志文件,默认启用journal = true# 刷写提交机制,默认是30ms或则100ms。较低的值,会更消耗磁盘的性能。此选项接受2和300毫秒之间的值:# 如果单块设备提供日志和数据文件,默认的日记提交时间间隔为100毫秒。如果不同的块设备提供的日志和数据文件,默认的日记提交的时间间隔为30毫秒。# journalCommitInterval=100# 启用定期记录CPU利用率和 I/O 等待,设置为true会强制mongodb每4s报告cpu利用率和io等待,把日志信息写到标准输出或日志文件。# 默认为false。开启日志会出现:1.Mon Jun 10 10:21:42.241 [snapshotthread] cpu: elapsed:4000 writelock: 0%# cpu = true# 用户认证,默认false。不需要认证。当设置为true时候,进入数据库需要auth验证,当数据库里没有用户,则不需要验证也可以操作。直到创建了第一个用户,之后操作都需要验证。# noauth = true# auth = true# 详细记录输出# verbose = true# 设置oplog记录等级 0=off (default) 1=W 2=R 3=both 7=W+some reads# diaglog = 0# 动态调试项# nocursors = true# 忽略查询提示# nohints = true# 指定的复制操作日志(OPLOG)的最大大小。mongod创建一个OPLOG的大小基于最大可用空间量。对于64位系统,OPLOG通常是5%的可用磁盘空间。# 一旦mongod第一次创建OPLOG,改变oplogSize将不会影响OPLOG的大小。# oplogSize = 1024# 指定存储身份验证信息的密钥文件的路径,默认缺省# keyFile = /path/to/keyfile# 最大连接数。默认值:取决于系统(即的ulimit和文件描述符)限制。MongoDB中不会限制其自身的连接。当设置大于系统的限制,则无效,以系统限制为准。这对于客户端创建很多“表”,# 允许连接超时而不关闭“表”的时候很有用。设置该值的高于连接池和总连接数的大小,以防止尖峰时 候的连接。注意:不能设置该值大于20000。# maxConns = 100# 强制验证客户端请求。2.4的默认设置为objcheck成为true,在早期版本objcheck默认为false。因为它强制验证客户端请求,确保客户端绝不插入无效文件到数据库中。# 对于嵌套文档的对象,会有一点性能影响。设置noobjcheck 关闭。# objcheck = true# 同上,默认false# noobjcheck = false# 进程ID,没有指定则启动时候就没有PID文件。默认缺省。# pidfilepath = /var/run/mongo.pid# 套接字文件,默认为false,有生成socket文件。当设置为true时,不会生成socket文件# nounixsocket = false# 套接字文件路径,默认/tmp# unixSocketPrefix = /tmp# 设置为true,修改数据目录存储模式,每个数据库的文件存储在DBPATH指定目录的不同的文件夹中。使用此选项,可以配置的MongoDB将数据存储在不同的磁盘设备上,以提高写入吞吐量或磁盘容量。默认为false。# 注意:要是在运行一段时间的数据库中,开启该参数,会导致原始的数据都会消失(注释参数则会回来)。因为数据目录都不同了,除非迁移现有的数据文件到directoryperdb产生的数据库目录中# directoryperdb = false# 是否支持ipv6,默认false# ipv6 = false# 是否允许JSONP访问通过一个HTTP接口,默认false。# jsonp = false# 是否禁止http接口,即28017 端口开启的服务。默认false,支持# nohttpinterface = false# 预分配方式。默认false:使用预分配方式来保证写入性能的稳定,预分配在后台进行,并且每个预分配的文件都用0进行填充。这会让MongoDB始终保持额外的空间和空余的数据文件,# 从而避免了数据增长过快而带来的分配磁盘空间引起的阻塞。设置noprealloc= true来禁用预分配的数据文件,会缩短启动时间,但在正常操作过程中,可能会导致性能显著下降。# noprealloc = false# 是否禁止脚本引擎。默认是false:不禁止。ture:禁止。# 要是设置成true:运行一些脚本的时候会出现:JavaScript execution failed: group command failed: { "ok" : 0, "errmsg" : "server-side JavaScript execution is disabled" }# noscripting = false# 是否禁止表扫描操作。默认false:不禁止,ture:禁止# 禁止要是执行表扫描会出现:error: { "$err" : "table scans not allowed:test.emp", "code" : 10111 }# notablescan = false# 命名空间的文件(即NS)的默认大小,默认16M,最大2G。所有新创建的默认大小命名空间的文件(即NS)。# 此选项不会影响现有的命名空间的文件的大小。默认值是16M字节,最大大小为2 GB。让小数据库不让浪费太多的磁盘空间,同时让大数据在磁盘上有连续的空间。# nssize = 16# 数据库分析等级设置。记录一些操作性能到标准输出或则指定的logpath的日志文件中,默认0:关闭。# 数据库分析可以影响数据库的性能,因为分析器必须记录和处理所有的数据库操作。所以在需要的时候用动态修改就可以了# 0:关,无分析。 1:开,仅包括慢操作。 2:开,包括所有操作。# 控制 Profiling  的开关和级别:2种# 第一种是直接在启动参数里直接进行设置或则启动MongoDB时加上–profile=级别,其信息保存在 生成的system.profile 中。# profile = 0# 记录profile分析的慢查询的时间,默认是100毫秒# slowms = 100# 配额,默认false。是否开启配置每个数据库的最多文件数的限制。当为true则用quotaFiles来配置最多文件的数量。# quota = false# 配额数量。每个数据库的数据文件数量的限制。此选项需要quota为true。默认为8# quotaFiles = 8# 使一个简单的 REST API,默认false,设置为true。# rest = true# 修复数据库操作,默认是false。设置为true时,启动后修复所有数据库,设置这个选项最好在命令行上,而不是在配置文件或控制脚本。# repair = true# 修复路径,默认是在dbpath路径下的_tmp 目录。# repairpath# 是否使用较小的默认文件。默认为false,不使用。设置为true,使用较小的默认数据文件大小。smallfiles减少数据文件的初始大小,并限制他们到512M,# 也减少了日志文件的大小,并限制他们到128M。如果数据库很大,各持有少量的数据,会导致mongodb创建很多文件,会影响性能。# smallfiles = true# 刷写数据到日志的频率,通过fsync操作数据。默认60秒。# 警告:如果设置为0,SYNCDELAY 不会同步到磁盘的内存映射文件。在生产系统上,不要设置这个值。# syncdelay = 60# 系统信息,默认false。设置为true,mongod会诊断系统有关的页面大小,数量的物理页面,可用物理??页面的数量输出到标准输出。# 当开启sysinfo参数的时候,只会打印信息,不会启动mongodb的程序。所以要关闭该参数,才能开启mongodb。# sysinfo = false# 升级。默认为false。当设置为true,指定DBPATH,升级磁盘上的数据格式的文件到最新版本。会影响数据库操作,更新元数据。大部分情况下,不需要设置该值。# upgrade = false# 是否使用内部诊断。默认false。# traceExceptions = false# 2.4的新参数,指定启动选项配置。想设置多个选项则用一个setParameter选项指定,可以setParameter的参数请见这里。# 声明setParameter设置在这个文件中,使用下面的格式:setParameter = <parameter>=<value># 例如: setParameter = syncdelay= 55,notablescan = true,journalCommitInterval = 50,traceExceptions = true# setParameter = # 使用此设置来配置复制副本集。指定一个副本集名称作为参数,所有主机都必须有相同的名称作为同一个副本集。# replSet = # 默认为false。在副本集下,设置为true,从一个dbpath里启用从库复制服务,该dbpath的数据库是主库的快照,可用于快速启用同步,# 否则的mongod将尝试执行初始同步。注意:如果数据不完全同步,mongod指定fastsync开启,secondary或slave与主永久不同步,这可能会导致显着的一致性问题。# fastsync = # 2.2版本出现的新参数,默认是all。可以设置的值有:all, none, and _id_only。只能在副本集(replSet)中使用。默认情况下,# secondary副本集的成员将加载所有索引到内存中(从OPLOG之前的操作有关的)。您可以修改此行为,使secondary只会加载_id索引。指定id或none,防止mongod的任何索引加载到内存。# replIndexPrefetch = # 主从复制的相关设置# master:默认为false,当设置为true,则配置当前实例作为主实例。# master = false# slave:默认为false,当设置为true,则配置当前实例作为从实例。# slave = true# 设置从库同步主库的延迟时间,用于从设置,默认为0。# slavedelay = 0# 是否自动重新同步.默认为false,用于从设置。设置为true,如果落后主超过10秒,会强制从自动重新同步。# 如果oplogSize太小,此设置可能有问题。如果OPLOG大小不足以存储主的变化状态和从的状态变化之间的差异,这种情况下强制重新同步是不必要的。# 当设置autoresync选项设置为false,10分钟内从不会进行大于1次的自动重新同步。# autoresync = false# 默认为空,格式为:<host><:port>。用于从实例的复制:设置从的时候指定该选项会让从复制指定主的实例# source = 127.0.0.1:30001# 默认为空,用于从选项,指定一个数据库进行复制。# only =

To explain the problem of automatic switching when the replica set encounters a failure: https://segmentfault.com/q/1010000022143836/a-1020000022144441

How does the program recognize the new IP address after automatic switching: Take Java as an example, new MongoClient(addrs) when the first parameter is an array, you should pass in all the nodes of this replica set.

2 MongoDB replica set deployment

2.1 Introduction to the replica set

MongoDB replica set (Replica Set) is actually a master-slave cluster with automatic failure recovery function. The biggest difference from master-slave replication is that there is no fixed "master node in the replica set; the entire replica set will select one node as the "master node". When it hangs up, elect a node from the remaining slave nodes to become the new "master node". There is always a primary node (primary) and one or more backup nodes (secondary) in the replica set.

In addition to primary and secondary, nodes in the replica set can also have the following roles:

For the basic concept of replica set, please refer to: https://blog.csdn.net/pengjunlee/article/details/83958794

Official help document: https://docs.mongodb.com/manual/replication/

The officially recommended minimum configuration of the replica set requires three nodes: one master node receives and processes all write operations, and two backup nodes synchronize the data of the master node by duplicating the operations of the master node.

2.2 Replica set configuration

2.2.1 Modify the configuration file

The IP of each node in the replica set is as follows:

192.168.171.10

192.168.171.11

192.168.171.12

First refer to the single-machine installation above, install MongoDB on the three servers

Then, modify the mongodb.conf configuration file of each node in turn, do the following configuration for all three nodes , add the relevant configuration of the replica set, and the content is as follows:

port=27017 	#端口,MongoDB默认端口为27017,注意防火墙的设置dbpath= /data/mongodb/data 	 #数据库存文件存放目录logpath= /data/mongodb/logs/mongodb.log 	#日志文件存放路径logappend=true 	#使用追加的方式写日志fork=true 	#以守护进程的方式运行,创建服务器进程maxConns=1000 	#最大同时连接数# noauth=true 	#不启用验证,默认不启用验证,这里也可以不用写journal=true 	#每次写入会记录一条操作日志(通过journal可以重新构造出写入的数据)。bind_ip = 0.0.0.0  	#这样就可外部访问 # 设置副本集名称,在各个配置文件中,其值必须相同replSet=rs0 oplogSize = 1024        # 指定的复制操作日志(OPLOG)的最大大小

2.2.2 Start the node

Start the node in the following three ways:

  1. mongod -f /home/mongodb-4.4.2/mongodb.conf
  2. mongod --config /home/mongodb-4.4.2/mongodb.conf
  3. systemctl start mongodb

So far, the three MongoDB instances have been started in the replica set mode , but they will not communicate with each other yet , and some configuration is still required.

2.2.3 Replica set initialization

Connect to any MongoDB instance among the three nodes through Shell, and execute the rs.initiate() method to initialize the replica set.

[[email protected] mongodb-4.4.2]# mongo 192.168.171.10:27017> conf=    {    "_id" : "rs0",    "members" : [        { "_id" : 0, "host" : "192.168.171.10:27017" },        { "_id" : 1, "host" : "192.168.171.11:27017" },        { "_id" : 2, "host" : "192.168.171.12:27017" }        ]    }> rs.initiate(conf){    "ok" : 1,    "operationTime" : Timestamp(1542247326, 1),    "$clusterTime" : {        "clusterTime" : Timestamp(1542247326, 1),        "signature" : {            "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),            "keyId" : NumberLong(0)        }    }}rs0:SECONDARY>

If you do not pass in any parameters when you execute the rs.initiate() method, MongoDB will initialize the replica set with the default configuration document, and you can add members to the replica set later through the rs.add() method.

2.2.4 Replica set update

# 向副本集中添加成员rs.add("192.168.171.15:27017") # 从副本集中删除成员rs.remove("192.168.171.15:27017") # 向副本集中添加仲裁rs.addArb("192.168.171.16:27017") # 向副本集中添加备份节点rs.add({"_id":3,"host":"192.168.171.17:27017","priority":0,"hidden":true})

Change the configuration:

# 更改副本集配置rs0:PRIMARY> var conf=rs.conf()rs0:PRIMARY> conf.members[1].priority = 55 # PRIMARY节点上执行如下命令rs0:PRIMARY> rs.reconfig(conf){    "ok" : 1,    "operationTime" : Timestamp(1542248518, 1),    "$clusterTime" : {        "clusterTime" : Timestamp(1542248518, 1),        "signature" : {            "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),            "keyId" : NumberLong(0)        }    }} # SECONDARY节点上执行如下命令,需增加 force 参数rs0:SECONDARY> rs.reconfig(conf,{force:true}){    "ok" : 1,    "operationTime" : Timestamp(1542248726, 1),    "$clusterTime" : {        "clusterTime" : Timestamp(1542248726, 1),        "signature" : {            "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),            "keyId" : NumberLong(0)        }    }}

To force a node to become Primary, the priority of the node can be set to the highest.

cfg = rs.conf()cfg.members[0].priority = 5cfg.members[1].priority = 1cfg.members[2].priority = 1rs.reconfig(cfg)

2.2.5 View replica set status information

1. View the configuration file

rs0:PRIMARY> rs.config(){        "_id" : "rst0",        "version" : 1,        "term" : 11,        "protocolVersion" : NumberLong(1),        "writeConcernMajorityJournalDefault" : true,        "members" : [                {                        "_id" : 0,                        "host" : "192.168.171.10:27017",                        "arbiterOnly" : false,                        "buildIndexes" : true,                        "hidden" : false,                        "priority" : 1,                        "tags" : {                         },                        "slaveDelay" : NumberLong(0),                        "votes" : 1                },                {                        "_id" : 1,                        "host" : "192.168.171.11:27017",                        "arbiterOnly" : false,                        "buildIndexes" : true,                        "hidden" : false,                        "priority" : 1,                        "tags" : {                         },                        "slaveDelay" : NumberLong(0),                        "votes" : 1                },                {                        "_id" : 2,                        "host" : "192.168.171.11:27017",                        "arbiterOnly" : false,                        "buildIndexes" : true,                        "hidden" : false,                        "priority" : 1,                        "tags" : {                         },                        "slaveDelay" : NumberLong(0),                        "votes" : 1                }        ],        "settings" : {                "chainingAllowed" : true,                "heartbeatIntervalMillis" : 2000,                "heartbeatTimeoutSecs" : 10,                "electionTimeoutMillis" : 10000,                "catchUpTimeoutMillis" : -1,                "catchUpTakeoverDelayMillis" : 30000,                "getLastErrorModes" : {                 },                "getLastErrorDefaults" : {                        "w" : 1,                        "wtimeout" : 0                },                "replicaSetId" : ObjectId("60b6070505cbf0635371a224")        }}

2. Check if it is the master node

rs0:PRIMARY> rs.isMaster(){        "topologyVersion" : {                "processId" : ObjectId("60b758c010a964d654243d01"),                "counter" : NumberLong(6)        },        "hosts" : [                "192.168.171.10:27017",                "192.168.171.11:27017",                "192.168.171.12:27017"        ],        "setName" : "rst0",        "setVersion" : 1,        "ismaster" : true,    # 是主节点        "secondary" : false,        "primary" : "188.2.138.33:27017",        "me" : "188.2.138.33:27017",        "electionId" : ObjectId("7fffffff000000000000000b"),        "lastWrite" : {                "opTime" : {                        "ts" : Timestamp(1622629065, 1),                        "t" : NumberLong(11)                },                "lastWriteDate" : ISODate("2021-06-02T10:17:45Z"),                "majorityOpTime" : {                        "ts" : Timestamp(1622629065, 1),                        "t" : NumberLong(11)                },                "majorityWriteDate" : ISODate("2021-06-02T10:17:45Z")        },        "maxBsonObjectSize" : 16777216,        "maxMessageSizeBytes" : 48000000,        "maxWriteBatchSize" : 100000,        "localTime" : ISODate("2021-06-02T10:17:50.350Z"),        "logicalSessionTimeoutMinutes" : 30,        "connectionId" : 14,        "minWireVersion" : 0,        "maxWireVersion" : 9,        "readOnly" : false,        "ok" : 1,        "$clusterTime" : {                "clusterTime" : Timestamp(1622629065, 1),                "signature" : {                        "hash" : BinData(0,"eT3i1BmMWoZHWh1S0EBs7W8IDn0="),                        "keyId" : NumberLong("6968765238703292419")                }        },        "operationTime" : Timestamp(1622629065, 1)}

3. View the information of the backup node pair, which can be viewed on any node

rs0:PRIMARY> db.printSecondaryReplicationInfo()source: 192.168.171.11:27017        syncedTo: Wed Jun 02 2021 18:20:05 GMT+0800 (CST)        0 secs (0 hrs) behind the primary source: 192.168.171.12:27017        syncedTo: Wed Jun 02 2021 18:20:05 GMT+0800 (CST)        0 secs (0 hrs) behind the primary

2.2.6 Test replica set

1. Insert data in the master node and observe from the node

rs0:PRIMARY> db.test.insert({"name":"mongodb中文网"})WriteResult({ "nInserted" : 1 })
rs0:SECONDARY> db.test.find(){ "_id" : ObjectId("60b75909a25d1962b9e06a17"), "name" : "mongodb中文网" }

2. The master node deletes data and observes from the node

rs0:PRIMARY> db.test.remove({'name': 'mongodb中文网'})WriteResult({ "nRemoved" : 1 })
# 主节点删除数据后,再次观察,无数据rs0:SECONDARY> db.test.find()rs0:SECONDARY>

Failover test:

1. Stop the master node, log in to the master node, and use the rs.isMaster() command or rs.status() to view the node information.

3 Turn on the security authentication of the database

MongoDB user and authentication details, portal:

https://blog.csdn.net/pengjunlee/article/details/84106877

3.1 Log in to the master node to create a super user

Create user reference: https://blog.csdn.net/weixin_34332905/article/details/88759759

You need to pay attention when creating a user. If you only want to create a super user to manage all databases, you must create it according to the following instructions: db.createUser({user:"root",pwd:"password",roles:["root "]})

Do not bind the user to admin, just set roles as root, otherwise, after the creation is complete, although it is a super user, it cannot operate other libraries except admin, and only has read permissions:

If you still make a mistake when creating it, just use the command to delete it directly: db.system.users.remove({user:"root"}) , if the user has been created and the configuration file has been opened for access rights, delete all Mongodb is stopped (first stop the slave library, and finally stop the main library), after stopping, close the access permissions in the configuration file, and then restart (first start the main library, then start the slave library), after completion, execute the delete command. can;

If it is a stand-alone machine, just start the deletion directly! ! !

Be sure to create on the master node, the slave nodes will automatically synchronize, remember, remember, remember! ! ! ! ! !

rs0:PRIMARY> use adminswitched to db adminrs0:PRIMARY> db.createUser({user:"root",pwd:"password",roles:["root"]})Successfully added user: { "user" : "root", "roles" : [ "root" ] }

3.2 Create a key file for replica set authentication

Stop the MongoDB service of all SECONDARY nodes first, then stop the MongoDB service of the PRIMARY node, and create a keyFile file on the server where the PRIMARY node is located.

# 将认证文件,放在跟配置文件,同一级目录openssl rand -base64 90 -out /home/mongodb-4.4.2/mongo.keyfile

There is a pit here. Please note that after the authentication file is created, its file attribute is the default 644. Here you need to change the file to 600, or 400, with read permission. The root user I used here is logged in If the system is configured, it is directly set to 600. If you do not set it, an error will be reported during startup. Must be set, must be set, must be set. . . . . . . . . . . . . . . .

chmod 600 /home/mongodb-4.4.2/mongo.keyfile 或者chmod 400 /home/mongodb-4.4.2/mongo.keyfile

All replica set nodes must use the same keyfile, which is generally generated on one machine and copied to other machines, and must have read permissions, otherwise an error will be reported in the future: permissions on /mongodb/replica_sets/myrs_27017/mongo .keyfile are too open Make
sure that the key file is consistent and the file location is arbitrary. However, in order to facilitate the search, it is recommended that each machine be placed in a fixed location and placed in a directory along with the configuration file.
Here the file is copied to multiple nodes.

scp /home/mongodb-4.4.2/mongo.keyfile  [email protected]:/home/mongodb-4.4.2/ scp /home/mongodb-4.4.2/mongo.keyfile  [email protected]:/home/mongodb-4.4.2/

3.3 Update MongoDB configuration file

All nodes are unified to add the following configuration

# 用户认证,默认false。不需要认证。当设置为true时候,进入数据库需要auth验证auth=true # 副本集节点配置,keyfile文件要一致keyFile=/home/mongodb-4.4.2/mongo.keyfile

3.4 Permission authentication of test replica set

After the change is completed, restart it, (first close the slave library, then close the main library, first enable the main library, then start the slave library)

After all is renewed, use the mongo command to log in to the database directly, insert data, and require permission authentication

Perform permission authentication

# 权限认证时,要先切换到admin集合rs0:PRIMARY> use adminswitched to db adminrs0:PRIMARY> db.auth("root", "password")1rs0:PRIMARY> 

After authentication, insert the data again, there is no problem:

rs0:PRIMARY> db.test.insert({"name":"mongodb中文网"})WriteResult({ "nInserted" : 1 })rs0:PRIMARY>

Or when logging in, you can log in directly as a super user. After logging in, you can directly operate the database without authorization authentication:

mongo -u "root" --authenticationDatabase "admin" -p'password'
[[email protected] mongodb-4.4.2]# mongo -u "root" --authenticationDatabase "admin" -p'password'MongoDB shell version v4.4.2connecting to: mongodb://127.0.0.1:27017/?authSource=admin&compressors=disabled&gssapiServiceName=mongodbImplicit session: session { "id" : UUID("3f7368d5-c556-4714-88d6-5a14837001cf") }MongoDB server version: 4.4.2---The server generated these startup warnings when booting:         2021-06-02T18:09:05.472+08:00: You are running this process as the root user, which is not recommended        2021-06-02T18:09:05.473+08:00: /sys/kernel/mm/transparent_hugepage/enabled is 'always'. We suggest setting it to 'never'        2021-06-02T18:09:05.473+08:00: /sys/kernel/mm/transparent_hugepage/defrag is 'always'. We suggest setting it to 'never'        2021-06-02T18:09:05.473+08:00: Soft rlimits too low        2021-06-02T18:09:05.473+08:00:         currentValue: 1024        2021-06-02T18:09:05.473+08:00:         recommendedMinimum: 64000------        Enable MongoDB's free cloud-based monitoring service, which will then receive and display        metrics about your deployment (disk utilization, CPU, operation statistics, etc).         The monitoring data will be available on a MongoDB website with a unique URL accessible to you        and anyone you share the URL with. MongoDB may use this information to make product        improvements and to suggest MongoDB products and deployment options to you.         To enable free monitoring, run the following command: db.enableFreeMonitoring()        To permanently disable this reminder, run the following command: db.disableFreeMonitoring()---rs0:PRIMARY> db.test.insert({"name":"mongodb中文网"})       # 插入成功WriteResult({ "nInserted" : 1 })rs0:PRIMARY> 

When logging in to view the data from the library, the following error is reported and directly input: rs.secondaryOk() can be solved

View data from the library, normal

rs0:SECONDARY> rs.secondaryOk()rs0:SECONDARY> db.test.find(){ "_id" : ObjectId("60b768ab5d120f3e93c58668"), "name" : "mongodb中文网" }rs0:SECONDARY> 

The replica set was created successfully

Build replica set reference: https://blog.csdn.net/pengjunlee/article/details/84101732?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522162251553016780357228258%2522%252C%2522scm%2522%253A%252220140713.130102334. .%2522%257D&request_id=162251553016780357228258&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduend~default-1-84101732.first_rank_v2_pc_rank_v29&utm_term=MongoDB%E5%89%AC%E9% 9B%86&spm=1018.2226.3001.4187

Summary of database permissions

MongoDB 中内置角色说明:read:提供读取所有非系统的集合(数据库)readWrite:提供读写所有非系统的集合(数据库)和读取所有角色的所有权限dbAdmin:提供执行管理任务的功能,例如与架构相关的任务,索引编制,收集统计信息。此角色不授予用户和角色管理权限。dbOwner:提供对数据库执行任何管理操作的功能。此角色组合了readWrite,dbAdmin 和 userAdmin 角色授予的权限。userAdmin :提供在当前数据库上创建和修改角色和用户的功能。由于 userAdmin 角色允许用户向任何用户(包括他们自己)授予任何权限,因此该角色还间接提供对数据库的超级用户访问权限,或者,如果作用于管理数据库,则提供对群集的访问权限。clusterAdmin :提供最佳的集群管理访问。此角色组合了 clusterManager,clusterMonitor 和 hostManager 角色授予的权限。此外,该角色还提供了 dropDatabase 操作。readAnyDatabase :仅在 admin 数据库中使用,提供所有数据库的读权限。readWriteAnyDatabase :仅在 admin 数据库中使用,提供所有数据库的读写权限userAdminAnyDatabase :仅在 admin 数据库中使用,提供与 userAdmin 相同的用户管理操作访问权限,允许用户向任何用户(包括他们自己)授予任何权限,因此该角色还间接提供超级用户访问权限。dbAdminAnyDatabase :仅在 admin 数据库中使用,提供与 dbAdmin 相同的数据库管理操作访问权限,该角色还在整个群集上提供 listDatabases 操作。root:仅在 admin 数据库中使用,提供超级权限 原文出自:www.hangge.com  转载请保留原文链接:https://www.hangge.com/blog/cache/detail_2613.html

Attached, user permissions reference: https://blog.csdn.net/Abel_Liujinquan/article/details/90732388