centos7 单机搭建MongoDB 4.2.5副本集群(支持事务)

一、下载&解压:

1、版本及下载:
版本:mongodb-4.2.5解压版
网盘下载地址:mongodb-linux-x86_64-rhel70-4.2.5(解压版).tgz
官网地址(需要登录才能下载):https://www.mongodb.com/download-center/enterprise

2、集群列表:

副本名 IP 端口 系统版本
1、从节点 192.168.101.150 40000 CentOS7.5.0
2、主节点 192.168.101.150 50000 CentOS7.5.0
3、从节点 192.168.101.150 60000 CentOS7.5.0

3、上传文件到集群服务器并解压、修改名称:

[root@localhost ~]# mkdir -p /opt
[root@localhost ~]# cd /opt/
[root@localhost opt]# rz
[root@localhost opt]# tar -zxvf mongodb-linux-x86_64-rhel70-4.2.5(解压版).tgz 
[root@localhost opt]# ll
total 129596
drwxr-xr-x. 3 root root       135 May 10 17:40 mongodb-linux-x86_64-rhel70-4.2.5
-rw-r--r--. 1 root root 132702741 Mar 31 19:11 mongodb-linux-x86_64-rhel70-4.2.5(解压版).tgz
[root@localhost opt]# 
[root@localhost opt]# mv mongodb-linux-x86_64-rhel70-4.2.5 mongodb-4.2.5
[root@localhost opt]# ll
total 129596
drwxr-xr-x. 3 root root       135 May 10 17:40 mongodb-4.2.5
-rw-r--r--. 1 root root 132702741 Mar 31 19:11 mongodb-linux-x86_64-rhel70-4.2.5(解压版).tgz
[root@localhost opt]#
[root@localhost opt]# cd mongodb-4.2.5/
[root@localhost mongodb-4.2.5]# ll
total 312
drwxr-xr-x. 2 root root    231 May 10 17:40 bin
-rw-r--r--. 1 root root  30608 Mar 24 12:47 LICENSE-Community.txt
-rw-r--r--. 1 root root  16726 Mar 24 12:47 MPL-2
-rw-r--r--. 1 root root   2617 Mar 24 12:47 README
-rw-r--r--. 1 root root  75405 Mar 24 12:47 THIRD-PARTY-NOTICES
-rw-r--r--. 1 root root 183512 Mar 24 12:49 THIRD-PARTY-NOTICES.gotools
[root@localhost mongodb-4.2.5]# 

二、创建资源目录:

4、创建40000、50000、60000端口对应的储存数据文件夹:

[root@localhost mongodb-4.2.5]# mkdir -p /opt/mongodb-4.2.5/40000/logs/
[root@localhost mongodb-4.2.5]# mkdir -p /opt/mongodb-4.2.5/40000/data/
[root@localhost mongodb-4.2.5]# mkdir -p /opt/mongodb-4.2.5/40000/key/
[root@localhost mongodb-4.2.5]# mkdir -p /opt/mongodb-4.2.5/40000/pid/
[root@localhost mongodb-4.2.5]# 
[root@localhost mongodb-4.2.5]# mkdir -p /opt/mongodb-4.2.5/50000/logs/
[root@localhost mongodb-4.2.5]# mkdir -p /opt/mongodb-4.2.5/50000/data/
[root@localhost mongodb-4.2.5]# mkdir -p /opt/mongodb-4.2.5/50000/key/
[root@localhost mongodb-4.2.5]# mkdir -p /opt/mongodb-4.2.5/50000/pid/
[root@localhost mongodb-4.2.5]# 
[root@localhost mongodb-4.2.5]# mkdir -p /opt/mongodb-4.2.5/60000/logs/
[root@localhost mongodb-4.2.5]# mkdir -p /opt/mongodb-4.2.5/60000/data/
[root@localhost mongodb-4.2.5]# mkdir -p /opt/mongodb-4.2.5/60000/key/
[root@localhost mongodb-4.2.5]# mkdir -p /opt/mongodb-4.2.5/60000/pid/

备注:

  • logs文件夹:存储日志
  • data文件夹:存储mongodb数据
  • key文件夹:存储密钥
  • pid文件夹:存放启动文件

三、创建 & 修改配置文件:

5、创建mongo-40000.confmongo-50000.confmongo-60000.conf配置文件:

[root@localhost mongodb-4.2.5]# touch /opt/mongodb-4.2.5/mongo-40000.conf
[root@localhost mongodb-4.2.5]# touch /opt/mongodb-4.2.5/mongo-50000.conf
[root@localhost mongodb-4.2.5]# touch /opt/mongodb-4.2.5/mongo-60000.conf

6、mongo-40000.conf配置:
修改命令:vi /opt/mongodb-4.2.5/mongo-40000.conf

systemLog:
   destination: file
   path: "/opt/mongodb-4.2.5/40000/logs/mongodb.log"
   logAppend: true
storage:
   dbPath: "/opt/mongodb-4.2.5/40000/data"
   journal:
      enabled: true
#   mmapv1:
#     smallFiles: true
   wiredTiger:
      engineConfig:
        configString: cache_size=500m
processManagement:
      fork: true
net:
   port: 40000
   bindIp: 0.0.0.0
setParameter:
   enableLocalhostAuthBypass: false
# 开启授权认证
security:
   authorization: disabled

replication:
   oplogSizeMB: 100
   replSetName: sszh
   enableMajorityReadConcern: true

7、mongo-50000.conf配置:
修改命令:vi /opt/mongodb-4.2.5/mongo-50000.conf

systemLog:
   destination: file
   path: "/opt/mongodb-4.2.5/50000/logs/mongodb.log"
   logAppend: true
storage:
   dbPath: "/opt/mongodb-4.2.5/50000/data"
   journal:
      enabled: true
#   mmapv1:
#     smallFiles: true
   wiredTiger:
      engineConfig:
        configString: cache_size=500m
processManagement:
      fork: true
net:
   port: 50000
   bindIp: 0.0.0.0
setParameter:
   enableLocalhostAuthBypass: false
# 开启授权认证
security:
   authorization: disabled

replication:
   oplogSizeMB: 100
   replSetName: sszh
   enableMajorityReadConcern: true

8、mongo-60000.conf配置:
修改命令:vi /opt/mongodb-4.2.5/mongo-60000.conf

systemLog:
   destination: file
   path: "/opt/mongodb-4.2.5/60000/logs/mongodb.log"
   logAppend: true
storage:
   dbPath: "/opt/mongodb-4.2.5/60000/data"
   journal:
      enabled: true
#   mmapv1:
#     smallFiles: true
   wiredTiger:
      engineConfig:
        configString: cache_size=500m
processManagement:
      fork: true
net:
   port: 60000
   bindIp: 0.0.0.0
setParameter:
   enableLocalhostAuthBypass: false
# 开启授权认证
security:
   authorization: disabled

replication:
   oplogSizeMB: 100
   replSetName: sszh
   enableMajorityReadConcern: true

四、创建 & 修改启动服务shell脚本:

9、创建start-40000start-50000start-60000的shell启动脚本:

[root@localhost mongodb-4.2.5]# touch /opt/mongodb-4.2.5/start-40000
[root@localhost mongodb-4.2.5]# touch /opt/mongodb-4.2.5/start-50000
[root@localhost mongodb-4.2.5]# touch /opt/mongodb-4.2.5/start-60000

10、start-40000内容:
修改命令:vi /opt/mongodb-4.2.5/start-40000

#!/bin/bash
count=`ps aux|grep mongo-40000.conf| grep -v grep |wc -l`
now=$(date "+%Y-%m-%d %H:%M:%S")
        #echo "服务启动总计条数:" $count
        if [ $count = 1 ]
        then
                exit
        fi
        echo $now "启动mongo-40000服务"
#启动数据库
/opt/mongodb-4.2.5/bin/mongod --config /opt/mongodb-4.2.5/mongo-40000.conf

11、start-50000内容:
修改命令:vi /opt/mongodb-4.2.5/start-50000

#!/bin/bash
count=`ps aux|grep mongo-50000.conf| grep -v grep |wc -l`
now=$(date "+%Y-%m-%d %H:%M:%S")
        #echo "服务启动总计条数:" $count
        if [ $count = 1 ]
        then
                exit
        fi
        echo $now "启动mongo-50000服务"
#启动数据库
/opt/mongodb-4.2.5/bin/mongod --config /opt/mongodb-4.2.5/mongo-50000.conf

12、start-60000内容:
修改命令:vi /opt/mongodb-4.2.5/start-60000

#!/bin/bash
count=`ps aux|grep mongo-60000.conf| grep -v grep |wc -l`
now=$(date "+%Y-%m-%d %H:%M:%S")
        if [ $count = 1 ]
        then
                exit
        fi
        echo $now "启动mongo-60000服务"
#启动数据库
/opt/mongodb-4.2.5/bin/mongod --config /opt/mongodb-4.2.5/mongo-60000.conf

**** 添加定时任务(一分钟执行一次),命令:

[root@localhost logs]# crontab -e

**** 在定时任务(一分钟执行一次)文本中添加如下内容,指定输出日志到每个库的 logs 目录下:

# 定时启动mongodb数据库,端口:40000
*/1 * * * * /opt/mongodb-4.2.5/start-40000 >> /opt/mongodb-4.2.5/40000/logs/mongo-40000-start-jianshi.log 2>&1

# 定时启动mongodb数据库,端口:50000
*/1 * * * * /opt/mongodb-4.2.5/start-50000 >> /opt/mongodb-4.2.5/50000/logs/mongo-50000-start-jianshi.log 2>&1

# 定时启动mongodb数据库,端口:60000
*/1 * * * * /opt/mongodb-4.2.5/start-60000 >> /opt/mongodb-4.2.5/60000/logs/mongo-60000-start-jianshi.log 2>&1

五、创建 & 修改停止服务shell脚本:

13、创建start-40000start-50000start-60000的shell启动脚本:

[root@localhost mongodb-4.2.5]# touch /opt/mongodb-4.2.5/stop-40000
[root@localhost mongodb-4.2.5]# touch /opt/mongodb-4.2.5/stop-50000
[root@localhost mongodb-4.2.5]# touch /opt/mongodb-4.2.5/stop-60000

14、stop-40000内容:
修改命令:vi /opt/mongodb-4.2.5/stop-40000

ps -ef|grep /opt/mongodb-4.2.5/mongo-40000.conf|grep -v grep|awk '{printf $2}'|xargs kill -9

15、stop-50000内容:
修改命令:vi /opt/mongodb-4.2.5/stop-50000

ps -ef|grep /opt/mongodb-4.2.5/mongo-50000.conf|grep -v grep|awk '{printf $2}'|xargs kill -9

16、stop-60000内容:
修改命令:vi /opt/mongodb-4.2.5/stop-60000

ps -ef|grep /opt/mongodb-4.2.5/mongo-60000.conf|grep -v grep|awk '{printf $2}'|xargs kill -9

六、赋予权限:

17、给/opt/mongodb-4.2.5/文件夹及全部文件添加权限(正式环境酌情考虑是否开放外部权限):

[root@localhost mongodb-4.2.5]# chmod -R 777 /opt/mongodb-4.2.5/

备注:

  • 参数-R是递归的意思
  • 777表示开放所有权限
  • 如果给所有人添加可执行权限:chmod a+x 文件名;
  • 如果给文件所有者添加可执行权限:chmod u+x 文件名;
  • 如果给所在组添加可执行权限:chmod g+x 文件名;
  • 如果给所在组以外的人添加可执行权限:chmod o+x 文件名;

七、启动mongodb:

18、先留意下如下错误信息:

  • 错误1:
    mongodb.conf文件粘贴时缺少字母,报错误信息如下:
    Unrecognized option: ystemLog.destination
    try ‘/opt/mongodb-4.2.5/bin/mongod --help’ for more information
  • 解决1:
    修改mongo.config文件,将 ystemLog 替换成 systemLog ,启动成功

19、启动mongodb服务:

[root@localhost mongodb-4.2.5]# sh start-40000 
about to fork child process, waiting until server is ready for connections.
forked process: 5866
child process started successfully, parent exiting
[root@localhost mongodb-4.2.5]# 
[root@localhost mongodb-4.2.5]# sh start-50000  
2020-05-10T18:27:42.526+0800 I  STORAGE  [main] Engine custom option: cache_size=500m
about to fork child process, waiting until server is ready for connections.
forked process: 5928
child process started successfully, parent exiting
[root@localhost mongodb-4.2.5]# 
[root@localhost mongodb-4.2.5]# sh start-60000 
2020-05-10T18:27:53.770+0800 I  STORAGE  [main] Engine custom option: cache_size=500m
about to fork child process, waiting until server is ready for connections.
forked process: 5976
child process started successfully, parent exiting
[root@localhost mongodb-4.2.5]# 

20、查看是否启动成功:

[root@localhost mongodb-4.2.5]# ps -ef|grep mongo
root       5866      1  1 18:27 ?        00:00:01 /opt/mongodb-4.2.5/bin/mongod --config /opt/mongodb-4.2.5/mongo-40000.conf
root       5928      1  1 18:27 ?        00:00:01 /opt/mongodb-4.2.5/bin/mongod --config /opt/mongodb-4.2.5/mongo-50000.conf
root       5976      1  1 18:27 ?        00:00:00 /opt/mongodb-4.2.5/bin/mongod --config /opt/mongodb-4.2.5/mongo-60000.conf
root       6054   3308  0 18:28 pts/0    00:00:00 grep --color=auto mongo
[root@localhost mongodb-4.2.5]# 

八、添加集群节点:

21、登录数据库192.168.101.150:40000,命令如下:

[root@localhost mongodb-4.2.5]# cd /opt/mongodb-4.2.5/bin/
[root@localhost bin]# ./mongo --port=50000
MongoDB shell version v4.2.5
connecting to: mongodb://127.0.0.1:50000/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("c06d47bb-3012-44d8-a53d-f26c6ce32e35") }
MongoDB server version: 4.2.5
Server has startup warnings: 
2020-05-10T18:35:07.614+0800 I  CONTROL  [initandlisten] ** WARNING: You are running this process as the root user, which is not recommended.
2020-05-10T18:35:07.614+0800 I  CONTROL  [initandlisten] 
2020-05-10T18:35:07.614+0800 I  CONTROL  [initandlisten] 
2020-05-10T18:35:07.614+0800 I  CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'.
2020-05-10T18:35:07.614+0800 I  CONTROL  [initandlisten] **        We suggest setting it to 'never'
2020-05-10T18:35:07.614+0800 I  CONTROL  [initandlisten] 
2020-05-10T18:35:07.614+0800 I  CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag is 'always'.
2020-05-10T18:35:07.614+0800 I  CONTROL  [initandlisten] **        We suggest setting it to 'never'
2020-05-10T18:35:07.614+0800 I  CONTROL  [initandlisten] 
---
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()
---

> 

22、登入后在 mongodb 命令行模式,执行 ’ > ’ 后面的命令:

> use admin
switched to db admin
> config={_id:"sszh", members:[{_id:0,host:'192.168.101.150:40000'}, {_id:1,host:'192.168.101.150:50000'}, {_id:2,host:'192.168.101.150:60000'}]};
{
        "_id" : "sszh",
        "members" : [
                {
                        "_id" : 0,
                        "host" : "192.168.101.150:40000"
                },
                {
                        "_id" : 1,
                        "host" : "192.168.101.150:50000"
                },
                {
                        "_id" : 2,
                        "host" : "192.168.101.150:60000"
                }
        ]
}
> rs.initiate(config)
{
        "ok" : 1,
        "$clusterTime" : {
                "clusterTime" : Timestamp(1589107742, 1),
                "signature" : {
                        "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
                        "keyId" : NumberLong(0)
                }
        },
        "operationTime" : Timestamp(1589107742, 1)
}
sszh:SECONDARY> 
sszh:PRIMARY> rs.status()
{
        "set" : "sszh",
        "date" : ISODate("2020-05-10T10:49:52.275Z"),
        "myState" : 1,
        "term" : NumberLong(1),
        "syncingTo" : "",
        "syncSourceHost" : "",
        "syncSourceId" : -1,
        "heartbeatIntervalMillis" : NumberLong(2000),
        "majorityVoteCount" : 2,
        "writeMajorityCount" : 2,
        "optimes" : {
                "lastCommittedOpTime" : {
                        "ts" : Timestamp(1589107783, 1),
                        "t" : NumberLong(1)
                },
                "lastCommittedWallTime" : ISODate("2020-05-10T10:49:43.308Z"),
                "readConcernMajorityOpTime" : {
                        "ts" : Timestamp(1589107783, 1),
                        "t" : NumberLong(1)
                },
                "readConcernMajorityWallTime" : ISODate("2020-05-10T10:49:43.308Z"),
                "appliedOpTime" : {
                        "ts" : Timestamp(1589107783, 1),
                        "t" : NumberLong(1)
                },
                "durableOpTime" : {
                        "ts" : Timestamp(1589107783, 1),
                        "t" : NumberLong(1)
                },
                "lastAppliedWallTime" : ISODate("2020-05-10T10:49:43.308Z"),
                "lastDurableWallTime" : ISODate("2020-05-10T10:49:43.308Z")
        },
        "lastStableRecoveryTimestamp" : Timestamp(1589107753, 3),
        "lastStableCheckpointTimestamp" : Timestamp(1589107753, 3),
        "electionCandidateMetrics" : {
                "lastElectionReason" : "electionTimeout",
                "lastElectionDate" : ISODate("2020-05-10T10:49:13.299Z"),
                "electionTerm" : NumberLong(1),
                "lastCommittedOpTimeAtElection" : {
                        "ts" : Timestamp(0, 0),
                        "t" : NumberLong(-1)
                },
                "lastSeenOpTimeAtElection" : {
                        "ts" : Timestamp(1589107742, 1),
                        "t" : NumberLong(-1)
                },
                "numVotesNeeded" : 2,
                "priorityAtElection" : 1,
                "electionTimeoutMillis" : NumberLong(10000),
                "numCatchUpOps" : NumberLong(0),
                "newTermStartDate" : ISODate("2020-05-10T10:49:13.306Z"),
                "wMajorityWriteAvailabilityDate" : ISODate("2020-05-10T10:49:14.729Z")
        },
        "members" : [
                {
                        "_id" : 0,
                        "name" : "192.168.101.150:40000",
                        "health" : 1,
                        "state" : 2,
                        "stateStr" : "SECONDARY",
                        "uptime" : 50,
                        "optime" : {
                                "ts" : Timestamp(1589107783, 1),
                                "t" : NumberLong(1)
                        },
                        "optimeDurable" : {
                                "ts" : Timestamp(1589107783, 1),
                                "t" : NumberLong(1)
                        },
                        "optimeDate" : ISODate("2020-05-10T10:49:43Z"),
                        "optimeDurableDate" : ISODate("2020-05-10T10:49:43Z"),
                        "lastHeartbeat" : ISODate("2020-05-10T10:49:51.314Z"),
                        "lastHeartbeatRecv" : ISODate("2020-05-10T10:49:50.722Z"),
                        "pingMs" : NumberLong(0),
                        "lastHeartbeatMessage" : "",
                        "syncingTo" : "192.168.101.150:50000",
                        "syncSourceHost" : "192.168.101.150:50000",
                        "syncSourceId" : 1,
                        "infoMessage" : "",
                        "configVersion" : 1
                },
                {
                        "_id" : 1,
                        "name" : "192.168.101.150:50000",
                        "health" : 1,
                        "state" : 1,
                        "stateStr" : "PRIMARY",
                        "uptime" : 886,
                        "optime" : {
                                "ts" : Timestamp(1589107783, 1),
                                "t" : NumberLong(1)
                        },
                        "optimeDate" : ISODate("2020-05-10T10:49:43Z"),
                        "syncingTo" : "",
                        "syncSourceHost" : "",
                        "syncSourceId" : -1,
                        "infoMessage" : "could not find member to sync from",
                        "electionTime" : Timestamp(1589107753, 1),
                        "electionDate" : ISODate("2020-05-10T10:49:13Z"),
                        "configVersion" : 1,
                        "self" : true,
                        "lastHeartbeatMessage" : ""
                },
                {
                        "_id" : 2,
                        "name" : "192.168.101.150:60000",
                        "health" : 1,
                        "state" : 2,
                        "stateStr" : "SECONDARY",
                        "uptime" : 50,
                        "optime" : {
                                "ts" : Timestamp(1589107783, 1),
                                "t" : NumberLong(1)
                        },
                        "optimeDurable" : {
                                "ts" : Timestamp(1589107783, 1),
                                "t" : NumberLong(1)
                        },
                        "optimeDate" : ISODate("2020-05-10T10:49:43Z"),
                        "optimeDurableDate" : ISODate("2020-05-10T10:49:43Z"),
                        "lastHeartbeat" : ISODate("2020-05-10T10:49:51.314Z"),
                        "lastHeartbeatRecv" : ISODate("2020-05-10T10:49:50.723Z"),
                        "pingMs" : NumberLong(0),
                        "lastHeartbeatMessage" : "",
                        "syncingTo" : "192.168.101.150:50000",
                        "syncSourceHost" : "192.168.101.150:50000",
                        "syncSourceId" : 1,
                        "infoMessage" : "",
                        "configVersion" : 1
                }
        ],
        "ok" : 1,
        "$clusterTime" : {
                "clusterTime" : Timestamp(1589107783, 1),
                "signature" : {
                        "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
                        "keyId" : NumberLong(0)
                }
        },
        "operationTime" : Timestamp(1589107783, 1)
}
sszh:PRIMARY> 

备注:

  • 语句 use admin 解释:使用admin数据库
  • 语句 config={} 解释:临时参数
  • 语句 rs.initiate(config) 解释:使用config临时参数初始化副本集
  • 语句 rs.status() 解释:查看集群状态
  • 集群状态参数 members[0].stateStr 解释:PRIMARY 表示主节点、SECONDARY表示从节点
  • PRIMARY 主节点:可读可写
  • SECONDARY 从节点:可读不可写
  • 更多参数解释:请查阅官网解释

23、使用工具连接测试:

  • Java连接副本集群url:mongodb://192.168.101.150:40000,192.168.101.150:50000,192.168.101.150:60000/?replicaSet=sszh
  • 连接工具:
    centos7 单机搭建MongoDB 4.2.5副本集群(支持事务)_第1张图片

九、问题及处理:

1、错误:Error accepting new connection on 0.0.0.0:40000: Too many open files 错误 导致 mongodb数据库进程停止:
解决:【运维笔记】linux最大文件句柄数:https://blog.csdn.net/seesun2012/article/details/106638194

2、错误:SyncSourceFeedback error sending update to 192.168.1.76:60000: InvalidSyncSource: Sync source was cleared. Was 192.168.1.76:60000 导致数据同步错误:
解决:同步服务器时钟,但是此教程是单台部署,不存在时钟不同步问题

3、【已解决】添加了IP限制的mongod重启出错:Job for mongod.service failed because the control process exited with error code
https://www.crifan.com/mongodb_add_multiple_ip_restriction_restart_mongod_fail_job_for_mongod_service_failed/

4、/mongod: /lib64/libc.so.6: version `GLIBC_2.14’ not found 问题解决:
https://blog.csdn.net/ym01213/article/details/90643437


























注:以上内容仅提供参考和交流,请勿用于商业用途,如有侵权联系本人删除!


持续更新中…

如有对思路不清晰或有更好的解决思路,欢迎与本人交流,微信:seesun2012(非紧急项目请加QQ群解答),QQ群:273557553
你遇到的问题是小编创作灵感的来源!


你可能感兴趣的:(MongoDB,数据库)