Mongodb数据库之主从复制配置实战
- 一、本次实践环境规划
- 1.环境规划
- 2.副本集介绍
- 二、检查本地Mongodb状态
- 1.检查主节点Mongodb状态
- 2.查看从节点mongodb状态
- 三、创建mongodb用户
- 1.进入主节点mongodb
- 2.创建admin账号
- 3.创建root账号
- 四、全部节点的统一配置
- 1.在主节点创建key文件
- 2.将key文件发送两个从节点
- 3.对相关目录及文件授权
- 4.编辑/etc/mongod.conf文件
- 5.重启mongodb服务
- 五、配置一主两从副本集
- 1.用户认证
- 2.配置副本集
- 六、查看mongodb主从状态
- 1.主库查看副本集配置
- 2.查看副本集状态
- 3.判断主从节点
- 七、测试mongodb主从切换
- 1.停止主库
- 2.查看从库状态
一、本次实践环境规划
1.环境规划
hostname | IP地址 | 系统版本 | 角色 |
---|---|---|---|
k8s-master | 192.168.3.201 | centos 7.6 | 主节点 |
k8s-node01 | 192.168.3.202 | centos 7.6 | 从节点 |
k8s-node02 | 192.168.3.203 | centos 7.6 | 从节点 |
2.副本集介绍
1.副本集在mongodb中是是一组 mongod保持相同的数据集过程,副本集提供冗余和高可用性,并且是所有生产部署的基础。
2.复制提供冗余并增加数据可用性,在不同数据库服务器上具有多个数据副本,复制可以提供一个级别的单一数据库服务器丢失的容错能力。
3.副本集至少需要3个成员,可以是一主两从,也可以是一主一从一仲裁节点,如果主节点挂掉,两个从节点会重新选举,找到一个从节点,将其提升为主。
二、检查本地Mongodb状态
1.检查主节点Mongodb状态
[root@k8s-master ~]# systemctl status mongod
● mongod.service - MongoDB Database Server
Loaded: loaded (/usr/lib/systemd/system/mongod.service; enabled; vendor preset: disabled)
Active: active (running) since Fri 2022-11-25 16:49:07 CST; 12min ago
Docs: https://docs.mongodb.org/manual
Main PID: 51072 (mongod)
CGroup: /system.slice/mongod.service
└─51072 /usr/bin/mongod -f /etc/mongod.conf
Nov 25 16:49:06 k8s-master systemd[1]: Starting MongoDB Database Server...
Nov 25 16:49:06 k8s-master mongod[51069]: about to fork child process, waiting until server is ready for connections.
Nov 25 16:49:06 k8s-master mongod[51069]: forked process: 51072
Nov 25 16:49:07 k8s-master systemd[1]: Started MongoDB Database Server.
2.查看从节点mongodb状态
[root@k8s-node01 ~]# systemctl status mongod
● mongod.service - MongoDB Database Server
Loaded: loaded (/usr/lib/systemd/system/mongod.service; enabled; vendor preset: disabled)
Active: active (running) since Fri 2022-11-25 16:47:32 CST; 14min ago
Docs: https://docs.mongodb.org/manual
Main PID: 47580 (mongod)
CGroup: /system.slice/mongod.service
└─47580 /usr/bin/mongod -f /etc/mongod.conf
Nov 25 16:47:31 k8s-node01 systemd[1]: Starting MongoDB Database Server...
Nov 25 16:47:31 k8s-node01 mongod[47577]: about to fork child process, waiting until server is ready for connections.
Nov 25 16:47:31 k8s-node01 mongod[47577]: forked process: 47580
Nov 25 16:47:32 k8s-node01 mongod[47577]: child process started successfully, parent exiting
Nov 25 16:47:32 k8s-node01 systemd[1]: Started MongoDB Database Server.
三、创建mongodb用户
1.进入主节点mongodb
[root@k8s-master ~]# mongo
MongoDB shell version v5.0.14
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("ff641498-a8f5-4ce4-bca4-1bb79fe06e37") }
MongoDB server version: 5.0.14
================
Warning: the "mongo" shell has been superseded by "mongosh",
which delivers improved usability and compatibility.The "mongo" shell has been deprecated and will be removed in
an upcoming release.
For installation instructions, see
https://docs.mongodb.com/mongodb-shell/install/
================
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
https://docs.mongodb.com/
Questions? Try the MongoDB Developer Community Forums
https://community.mongodb.com
---
The server generated these startup warnings when booting:
2022-11-25T16:49:07.312+08:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
2022-11-25T16:49:07.312+08:00: /sys/kernel/mm/transparent_hugepage/enabled is 'always'. We suggest setting it to 'never'
2022-11-25T16:49:07.312+08:00: /sys/kernel/mm/transparent_hugepage/defrag is 'always'. We suggest setting it to 'never'
---
---
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()
---
>
2.创建admin账号
use admin;
db.createUser({
user: "admin",
pwd: "admin",
roles: [
{role: "userAdminAnyDatabase",db: "admin"}
]
}
)
3.创建root账号
> use admin;
switched to db admin
> db.auth("admin", "admin")
1
db.createUser({
user: "root",
pwd: "redhat",
roles: [ "root" ]
}
)
四、全部节点的统一配置
1.在主节点创建key文件
[root@k8s-master ~]# mkdir -p /data/mongodb/
[root@k8s-master ~]# openssl rand -base64 666 > /data/mongodb/mongodb.key
[root@k8s-master ~]#
2.将key文件发送两个从节点
[root@k8s-master ~]# scp /data/mongodb/mongodb.key root@192.168.3.203:/data/mongodb/
mongodb.key 100% 902 1.3MB/s 00:00
[root@k8s-master ~]# scp /data/mongodb/mongodb.key root@192.168.3.202:/data/mongodb/
mongodb.key 100% 902 936.6KB/s 00:00
[root@k8s-master ~]#
3.对相关目录及文件授权
3个节点都要进行授权操作
chown mongod:mongod -R /data/mongodb/
chmod 600 /data/mongodb/mongodb.key
4.编辑/etc/mongod.conf文件
修改/etc/mongod.conf 文件,3个节点全部都要配置。
[root@k8s-master ~]# cat /etc/mongod.conf
systemLog:
destination: file
logAppend: true
path: /var/log/mongodb/mongod.log
storage:
dbPath: /var/lib/mongo
journal:
enabled: true
processManagement:
fork: true # fork and run in background
pidFilePath: /var/run/mongodb/mongod.pid # location of pidfile
timeZoneInfo: /usr/share/zoneinfo
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:
authorization: enabled
keyFile: /data/mongodb/mongodb.key
clusterAuthMode: keyFile
replication:
replSetName: rs0
oplogSizeMB: 5000
5.重启mongodb服务
[root@k8s-master ~]# systemctl restart mongod
[root@k8s-master ~]# systemctl status mongod
● mongod.service - MongoDB Database Server
Loaded: loaded (/usr/lib/systemd/system/mongod.service; enabled; vendor preset: disabled)
Active: active (running) since Fri 2022-11-25 19:25:17 CST; 6s ago
Docs: https://docs.mongodb.org/manual
Process: 71895 ExecStart=/usr/bin/mongod $OPTIONS (code=exited, status=0/SUCCESS)
Process: 71893 ExecStartPre=/usr/bin/chmod 0755 /var/run/mongodb (code=exited, status=0/SUCCESS)
Process: 71892 ExecStartPre=/usr/bin/chown mongod:mongod /var/run/mongodb (code=exited, status=0/SUCCESS)
Process: 71889 ExecStartPre=/usr/bin/mkdir -p /var/run/mongodb (code=exited, status=0/SUCCESS)
Main PID: 71898 (mongod)
Tasks: 48
Memory: 163.5M
CGroup: /system.slice/mongod.service
└─71898 /usr/bin/mongod -f /etc/mongod.conf
Nov 25 19:25:17 k8s-master systemd[1]: Starting MongoDB Database Server...
Nov 25 19:25:17 k8s-master mongod[71895]: about to fork child process, waiting until server is ready for connections.
Nov 25 19:25:17 k8s-master mongod[71895]: forked process: 71898
Nov 25 19:25:17 k8s-master mongod[71895]: child process started successfully, parent exiting
Nov 25 19:25:17 k8s-master systemd[1]: Started MongoDB Database Server.
[root@k8s-master ~]#
五、配置一主两从副本集
1.用户认证
> use admin;
switched to db admin
> db.auth("root", "redhat")
1
>
2.配置副本集
rs.initiate({
_id : "rs0",
members: [
{ _id: 0, host: "192.168.3.201:27017" },
{ _id: 1, host: "192.168.3.202:27017" },
{ _id: 2, host: "192.168.3.203:27017" }
]
})
六、查看mongodb主从状态
1.主库查看副本集配置
rs0:PRIMARY> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
rs0:PRIMARY>
rs0:PRIMARY> rs.config()
{
"_id" : "rs0",
"version" : 1,
"term" : 1,
"members" : [
{
"_id" : 0,
"host" : "192.168.3.201:27017",
"arbiterOnly" : false,
"buildIndexes" : true,
"hidden" : false,
"priority" : 1,
"tags" : {
},
"secondaryDelaySecs" : NumberLong(0),
"votes" : 1
},
{
"_id" : 1,
"host" : "192.168.3.202:27017",
"arbiterOnly" : false,
"buildIndexes" : true,
"hidden" : false,
"priority" : 1,
"tags" : {
},
"secondaryDelaySecs" : NumberLong(0),
"votes" : 1
},
{
"_id" : 2,
"host" : "192.168.3.203:27017",
"arbiterOnly" : false,
"buildIndexes" : true,
"hidden" : false,
"priority" : 1,
"tags" : {
},
"secondaryDelaySecs" : NumberLong(0),
"votes" : 1
}
],
"protocolVersion" : NumberLong(1),
"writeConcernMajorityJournalDefault" : true,
"settings" : {
"chainingAllowed" : true,
"heartbeatIntervalMillis" : 2000,
"heartbeatTimeoutSecs" : 10,
"electionTimeoutMillis" : 10000,
"catchUpTimeoutMillis" : -1,
"catchUpTakeoverDelayMillis" : 30000,
"getLastErrorModes" : {
},
"getLastErrorDefaults" : {
"w" : 1,
"wtimeout" : 0
},
"replicaSetId" : ObjectId("6380cfba32d52557ab398cd4")
}
}
rs0:PRIMARY>
2.查看副本集状态
s0:PRIMARY> rs.status()
{
"set" : "rs0",
"date" : ISODate("2022-11-25T14:26:45.747Z"),
"myState" : 1,
"term" : NumberLong(1),
"syncSourceHost" : "",
"syncSourceId" : -1,
"heartbeatIntervalMillis" : NumberLong(2000),
"majorityVoteCount" : 2,
"writeMajorityCount" : 2,
"votingMembersCount" : 3,
"writableVotingMembersCount" : 3,
"optimes" : {
"lastCommittedOpTime" : {
"ts" : Timestamp(1669386401, 1),
"t" : NumberLong(1)
},
"lastCommittedWallTime" : ISODate("2022-11-25T14:26:41.054Z"),
"readConcernMajorityOpTime" : {
"ts" : Timestamp(1669386401, 1),
"t" : NumberLong(1)
},
"appliedOpTime" : {
"ts" : Timestamp(1669386401, 1),
"t" : NumberLong(1)
},
"durableOpTime" : {
"ts" : Timestamp(1669386401, 1),
"t" : NumberLong(1)
},
"lastAppliedWallTime" : ISODate("2022-11-25T14:26:41.054Z"),
"lastDurableWallTime" : ISODate("2022-11-25T14:26:41.054Z")
},
"lastStableRecoveryTimestamp" : Timestamp(1669386341, 1),
"electionCandidateMetrics" : {
"lastElectionReason" : "electionTimeout",
"lastElectionDate" : ISODate("2022-11-25T14:23:01.020Z"),
"electionTerm" : NumberLong(1),
"lastCommittedOpTimeAtElection" : {
"ts" : Timestamp(1669386170, 1),
"t" : NumberLong(-1)
},
"lastSeenOpTimeAtElection" : {
"ts" : Timestamp(1669386170, 1),
"t" : NumberLong(-1)
},
"numVotesNeeded" : 2,
"priorityAtElection" : 1,
"electionTimeoutMillis" : NumberLong(10000),
"numCatchUpOps" : NumberLong(0),
"newTermStartDate" : ISODate("2022-11-25T14:23:01.035Z"),
"wMajorityWriteAvailabilityDate" : ISODate("2022-11-25T14:23:01.566Z")
},
"members" : [
{
"_id" : 0,
"name" : "192.168.3.201:27017",
"health" : 1,
"state" : 1,
"stateStr" : "PRIMARY",
"uptime" : 1785,
"optime" : {
"ts" : Timestamp(1669386401, 1),
"t" : NumberLong(1)
},
"optimeDate" : ISODate("2022-11-25T14:26:41Z"),
"lastAppliedWallTime" : ISODate("2022-11-25T14:26:41.054Z"),
"lastDurableWallTime" : ISODate("2022-11-25T14:26:41.054Z"),
"syncSourceHost" : "",
"syncSourceId" : -1,
"infoMessage" : "",
"electionTime" : Timestamp(1669386181, 1),
"electionDate" : ISODate("2022-11-25T14:23:01Z"),
"configVersion" : 1,
"configTerm" : 1,
"self" : true,
"lastHeartbeatMessage" : ""
},
{
"_id" : 1,
"name" : "192.168.3.202:27017",
"health" : 1,
"state" : 2,
"stateStr" : "SECONDARY",
"uptime" : 235,
"optime" : {
"ts" : Timestamp(1669386401, 1),
"t" : NumberLong(1)
},
"optimeDurable" : {
"ts" : Timestamp(1669386401, 1),
"t" : NumberLong(1)
},
"optimeDate" : ISODate("2022-11-25T14:26:41Z"),
"optimeDurableDate" : ISODate("2022-11-25T14:26:41Z"),
"lastAppliedWallTime" : ISODate("2022-11-25T14:26:41.054Z"),
"lastDurableWallTime" : ISODate("2022-11-25T14:26:41.054Z"),
"lastHeartbeat" : ISODate("2022-11-25T14:26:45.117Z"),
"lastHeartbeatRecv" : ISODate("2022-11-25T14:26:44.113Z"),
"pingMs" : NumberLong(0),
"lastHeartbeatMessage" : "",
"syncSourceHost" : "192.168.3.201:27017",
"syncSourceId" : 0,
"infoMessage" : "",
"configVersion" : 1,
"configTerm" : 1
},
{
"_id" : 2,
"name" : "192.168.3.203:27017",
"health" : 1,
"state" : 2,
"stateStr" : "SECONDARY",
"uptime" : 235,
"optime" : {
"ts" : Timestamp(1669386401, 1),
"t" : NumberLong(1)
},
"optimeDurable" : {
"ts" : Timestamp(1669386401, 1),
"t" : NumberLong(1)
},
"optimeDate" : ISODate("2022-11-25T14:26:41Z"),
"optimeDurableDate" : ISODate("2022-11-25T14:26:41Z"),
"lastAppliedWallTime" : ISODate("2022-11-25T14:26:41.054Z"),
"lastDurableWallTime" : ISODate("2022-11-25T14:26:41.054Z"),
"lastHeartbeat" : ISODate("2022-11-25T14:26:45.117Z"),
"lastHeartbeatRecv" : ISODate("2022-11-25T14:26:44.113Z"),
"pingMs" : NumberLong(0),
"lastHeartbeatMessage" : "",
"syncSourceHost" : "192.168.3.201:27017",
"syncSourceId" : 0,
"infoMessage" : "",
"configVersion" : 1,
"configTerm" : 1
}
],
"ok" : 1,
"$clusterTime" : {
"clusterTime" : Timestamp(1669386401, 1),
"signature" : {
"hash" : BinData(0,"TkiPRtGCEbUH9TE/Ho9E14B6QNc="),
"keyId" : NumberLong("7169959051789336581")
}
},
"operationTime" : Timestamp(1669386401, 1)
}
rs0:PRIMARY>
3.判断主从节点
“primary” : “192.168.3.201:27017”,显示192.168.3.201主机为主节点
rs0:PRIMARY> rs.isMaster()
{
"topologyVersion" : {
"processId" : ObjectId("6380c9ac32d52557ab398c3c"),
"counter" : NumberLong(6)
},
"hosts" : [
"192.168.3.201:27017",
"192.168.3.202:27017",
"192.168.3.203:27017"
],
"setName" : "rs0",
"setVersion" : 1,
"ismaster" : true,
"secondary" : false,
"primary" : "192.168.3.201:27017",
"me" : "192.168.3.201:27017",
"electionId" : ObjectId("7fffffff0000000000000001"),
"lastWrite" : {
"opTime" : {
"ts" : Timestamp(1669386501, 1),
"t" : NumberLong(1)
},
"lastWriteDate" : ISODate("2022-11-25T14:28:21Z"),
"majorityOpTime" : {
"ts" : Timestamp(1669386501, 1),
"t" : NumberLong(1)
},
"majorityWriteDate" : ISODate("2022-11-25T14:28:21Z")
},
"maxBsonObjectSize" : 16777216,
"maxMessageSizeBytes" : 48000000,
"maxWriteBatchSize" : 100000,
"localTime" : ISODate("2022-11-25T14:28:22.294Z"),
"logicalSessionTimeoutMinutes" : 30,
"connectionId" : 1,
"minWireVersion" : 0,
"maxWireVersion" : 13,
"readOnly" : false,
"ok" : 1,
"$clusterTime" : {
"clusterTime" : Timestamp(1669386501, 1),
"signature" : {
"hash" : BinData(0,"Sv8XmUFZHsjR0SbeOwNA29eggs4="),
"keyId" : NumberLong("7169959051789336581")
}
},
"operationTime" : Timestamp(1669386501, 1)
七、测试mongodb主从切换
1.停止主库
[root@k8s-master ~]# systemctl stop mongod.service
[root@k8s-master ~]#
2.查看从库状态
[root@k8s-node01 ~]# mongo
MongoDB shell version v5.0.14
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("a204a521-8a32-43b1-bc4b-3197756c4a19") }
MongoDB server version: 5.0.14
================
Warning: the "mongo" shell has been superseded by "mongosh",
which delivers improved usability and compatibility.The "mongo" shell has been deprecated and will be removed in
an upcoming release.
For installation instructions, see
https://docs.mongodb.com/mongodb-shell/install/
================
rs0:PRIMARY>