实验:搭建mongodb复制集()

 本实验中,我们通过三台服务器搭建一个最简单的复制集

1、关闭防火墙

输入命令“systemctl status firewalld.service”并按下回车键

在命令行中输入systemctl stop firewalld.service命令,进行关闭防火墙

再在命令行中输入命令“systemctl disable firewalld.service”命令,即可永久关闭防火墙

[root@localhost wsq]# systemctl status firewalld.service
● firewalld.service - firewalld - dynamic firewall daemon
   Loaded: loaded (/usr/lib/systemd/system/firewalld.service; enabled; vendor preset: enabled)
   Active: active (running) since 日 2021-03-28 09:57:29 CST; 54min ago
     Docs: man:firewalld(1)
 Main PID: 6689 (firewalld)
    Tasks: 2
   CGroup: /system.slice/firewalld.service
           └─6689 /usr/bin/python -Es /usr/sbin/firewalld --nofork --nopid

3月 28 09:57:22 localhost.localdomain systemd[1]: Starting firewalld - dynam...
3月 28 09:57:29 localhost.localdomain systemd[1]: Started firewalld - dynami...
Hint: Some lines were ellipsized, use -l to show in full.
[root@localhost wsq]# systemctl stop firewalld.service
[root@localhost wsq]# systemctl disable firewalld.service
Removed symlink /etc/systemd/system/multi-user.target.wants/firewalld.service.
Removed symlink /etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service.

2、查看三台服务器的ip

通过ip addr

[root@localhost wsq]# ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 00:0c:29:a8:d9:af brd ff:ff:ff:ff:ff:ff
    inet 172.18.87.20/23 brd 172.18.87.255 scope global noprefixroute dynamic ens33
       valid_lft 6782sec preferred_lft 6782sec
    inet6 fe80::907a:cf7:aca7:b430/64 scope link noprefixroute 
       valid_lft forever preferred_lft forever
3: virbr0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default qlen 1000
    link/ether 52:54:00:32:fc:ef brd ff:ff:ff:ff:ff:ff
    inet 192.168.122.1/24 brd 192.168.122.255 scope global virbr0
       valid_lft forever preferred_lft forever
4: virbr0-nic: <BROADCAST,MULTICAST> mtu 1500 qdisc pfifo_fast master virbr0 state DOWN group default qlen 1000
    link/ether 52:54:00:32:fc:ef brd ff:ff:ff:ff:ff:ff

其中inet 172.18.87.20为第一台服务器Ip

通过查询得知三台服务器的ip 

服务器1 172.18.87.20
服务器2 172.18.86.119
服务器3 172.18.86.227

3、安装mongodb

从官网下载的默认地址为下载,解压安装
[root@localhost wsq]# cd /home/wsq/下载
[root@localhost 下载]# tar zxvf mongodb-linux-x86_64-rhel70-4.0.23.tgz
mongodb-linux-x86_64-rhel70-4.0.23/THIRD-PARTY-NOTICES.gotools
mongodb-linux-x86_64-rhel70-4.0.23/README
mongodb-linux-x86_64-rhel70-4.0.23/THIRD-PARTY-NOTICES
mongodb-linux-x86_64-rhel70-4.0.23/MPL-2
mongodb-linux-x86_64-rhel70-4.0.23/LICENSE-Community.txt
mongodb-linux-x86_64-rhel70-4.0.23/bin/mongodump
mongodb-linux-x86_64-rhel70-4.0.23/bin/mongorestore
mongodb-linux-x86_64-rhel70-4.0.23/bin/mongoexport
mongodb-linux-x86_64-rhel70-4.0.23/bin/mongoimport
mongodb-linux-x86_64-rhel70-4.0.23/bin/mongostat
mongodb-linux-x86_64-rhel70-4.0.23/bin/mongotop
mongodb-linux-x86_64-rhel70-4.0.23/bin/bsondump
mongodb-linux-x86_64-rhel70-4.0.23/bin/mongofiles
mongodb-linux-x86_64-rhel70-4.0.23/bin/mongoreplay
mongodb-linux-x86_64-rhel70-4.0.23/bin/mongod
mongodb-linux-x86_64-rhel70-4.0.23/bin/mongos
mongodb-linux-x86_64-rhel70-4.0.23/bin/mongo
mongodb-linux-x86_64-rhel70-4.0.23/bin/install_compass
[root@localhost 下载]# mv mongodb-linux-x86_64-rhel70-4.0.23 /usr/local/mongodb
[root@localhost 下载]# cd /usr/local/mongodb
[root@localhost mongodb]# echo 'export PATH=$PATH:/usr/local/mongodb/bin'  >> /etc/profile
[root@localhost mongodb]# source  /etc/profile

4、复制集的创建

4.1副本集的角色

副本集主要有两种类型和三种角色

两种类型:

  1. 主节点(Primary):数据操作的主要连接点,允许读和写操作
  2. 从节点(Secondaries):数据冗余备份节点,可以读或选举为主节点

角色:

MongoDB主要有三种角色

主要成员(Primary):主节点,主要接收所有的写操作

副本成员(Replicate):主从节点通过备份操作以维护相同的数据集。只支持读操作,不支持写操作。拥有选举能力

仲裁者(Arbiter):不保留任何数据的副本,只具有选举作用。副本成员也可以作为仲裁者。

实验:搭建mongodb复制集()

 

4.2副本集的创建

我们本次实验以一主一副一仲裁为案例搭建副本集。

本次使用三台服务器。服务器不够的同学,可以在一台服务器进行操作,操作步骤类似,只需要配置三个不同的端口即可。

三台机器的ip分别为:172.18.87.20  172.18.86.119  172.18.86.227

4.2.1 创建主节点(即在第一台服务器上实现此操作)

创建存放数据和日志的目录

mkdir -p /mongodb/replica_sets/rs_1/log
mkdir -p /mongodb/replica_sets/rs_1/data/db

创建配置文件

vim /mongodb/replica_sets/rs_1/mongod.conf

mongod.conf

systemLog:
  #日志输出为文件 
  destination: file
  #日志文件的路径 
  path: "/mongodb/replica_sets/rs_1/log/mongod.log"
  #mongod实例重新启动时,会将新条目附加到现有日志文件的末尾。 
  logAppend: true 
storage: 
  #数据目录。
  dbPath: "/mongodb/replica_sets/rs_1/data/db" 
  journal:
    #启用持久性日志
    enabled: true
processManagement:
  #启用守护进程模式。 
  fork: true
  #指定进程ID的文件位置
  pidFilePath: "/mongodb/replica_sets/rs_1/log/mongod.pid"
net:
  #服务实例绑定的IP
  bindIp: 0.0.0.0
  #绑定的端口 
  port: 27017
replication:
  #副本集的名称 
  replSetName: myrs

启动节点

/usr/local/mongodb/bin/mongod -f /mongodb/replica_sets/rs_1/mongod.conf

4.2.2 创建副本节点

创建存放数据和日志的目录

mkdir -p /mongodb/replica_sets/rs_2/log
mkdir -p /mongodb/replica_sets/rs_2/data/db

创建配置文件

vim /mongodb/replica_sets/rs_2/mongod.conf

mongod.conf

systemLog:
  #日志输出为文件 
  destination: file
  #日志文件的路径 
  path: "/mongodb/replica_sets/rs_2/log/mongod.log"
  #mongod实例重新启动时,会将新条目附加到现有日志文件的末尾。 
  logAppend: true 
storage: 
  #数据目录。
  dbPath: "/mongodb/replica_sets/rs_2/data/db" 
  journal:
    #启用持久性日志
    enabled: true
processManagement:
  #启用守护进程模式。 
  fork: true
  #指定进程ID的文件位置
  pidFilePath: "/mongodb/replica_sets/rs_2/log/mongod.pid"
net:
  #服务实例绑定的IP 
  bindIp: 0.0.0.0
  #绑定的端口 
  port: 27017
replication:
  #副本集的名称 
  replSetName: myrs

启动节点

/usr/local/mongodb/bin/mongod -f /mongodb/replica_sets/rs_2/mongod.conf

4.2.3 创建仲裁节点

创建存放数据和日志的目录

mkdir -p /mongodb/replica_sets/rs_3/log
mkdir -p /mongodb/replica_sets/rs_3/data/db

创建配置文件

vim /mongodb/replica_sets/rs_3/mongod.conf

mongod.conf

systemLog:
  #日志输出为文件 
  destination: file
  #日志文件的路径 
  path: "/mongodb/replica_sets/rs_3/log/mongod.log"
  #mongod实例重新启动时,会将新条目附加到现有日志文件的末尾。 
  logAppend: true 
storage: 
  #数据目录。
  dbPath: "/mongodb/replica_sets/rs_3/data/db" 
  journal:
    #启用持久性日志
    enabled: true
processManagement:
  #启用守护进程模式。 
  fork: true
  #指定进程ID的文件位置
  pidFilePath: "/mongodb/replica_sets/rs_3/log/mongod.pid"
net:
  #服务实例绑定的IP 
  bindIp: 0.0.0.0
  #绑定的端口 
  port: 27017
replication:
  #副本集的名称 
  replSetName: myrs

启动节点

/usr/local/mongodb/bin/mongod -f /mongodb/replica_sets/rs_3/mongod.conf

4.3 初始化副本集和主节点

连接任意一个节点(最好连接我们认为的主节点)

/usr/local/mongodb/bin/mongo --host=172.18.87.20 --port=27017

在配置副本集之前,现在的mongodb几乎所有的命令都是无法使用的。

初始化副本集

rs.initiate()
> rs.initiate()
{
	"info2" : "no configuration specified. Using a default configuration for the set",
	"me" : "localhost.localdomain:27017",
	"ok" : 1,
	"operationTime" : Timestamp(1616909801, 1),
	"$clusterTime" : {
		"clusterTime" : Timestamp(1616909801, 1),
		"signature" : {
			"hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
			"keyId" : NumberLong(0)
		}
	}
}
myrs:OTHER> 回车
myrs:PRIMARY> 

ok的值为1则初始化成功

注意:这里显示的me不是ip:端口,需要修改

rs.conf()

展示出配置,可以看到host,我们需要修改的就是这个

# 导出配置到config
config = rs.conf()
# 设置第1个节点的优先级是10
config.members[0].host="172.18.87.20:27017"
# 重载配置
rs.reconfig(config)

4.4 查看副本集配置和状态

查看副本集配置

rs.conf()
或者
rs.config()
myrs:PRIMARY> rs.conf()
{
	"_id" : "myrs",
	"version" : 2,
	"protocolVersion" : NumberLong(1),
	"writeConcernMajorityJournalDefault" : true,
	"members" : [
		{
			"_id" : 0,
			"host" : "172.18.87.20: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("606015e97a99916d7dbeeb2e")
	}
}
myrs:PRIMARY> 

 

_id:"rs" 副本集名称

members:副本集成员数组

arbiterOnly:该成员是否为仲裁节点

priority:优先级权重值

rs.conf() 命令,本质上其实是查询 local 库中 system.replset 集合中的数据

db.system.replset.find()

查看副本集状态

rs.status()

set:"rs":副本集名称

myState: 1:说明状态正常

members:副本集成员数组

stateStr:该成员的角色

health:1:该节点是健康的

4.5 添加副本

在主节点,添加其他成员到副本集

rs.add(host, arbiterOnly)
rs.add("172.18.86.119:27017")
rs.status()
myrs:PRIMARY> rs.add("172.18.86.119:27017")
{
	"ok" : 1,
	"operationTime" : Timestamp(1616910574, 1),
	"$clusterTime" : {
		"clusterTime" : Timestamp(1616910574, 1),
		"signature" : {
			"hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
			"keyId" : NumberLong(0)
		}
	}
}
myrs:PRIMARY> rs.status()
{
	"set" : "myrs",
	"date" : ISODate("2021-03-28T05:49:43.568Z"),
	"myState" : 1,
	"term" : NumberLong(1),
	"syncingTo" : "",
	"syncSourceHost" : "",
	"syncSourceId" : -1,
	"heartbeatIntervalMillis" : NumberLong(2000),
	"optimes" : {
		"lastCommittedOpTime" : {
			"ts" : Timestamp(1616910574, 1),
			"t" : NumberLong(1)
		},
		"readConcernMajorityOpTime" : {
			"ts" : Timestamp(1616910574, 1),
			"t" : NumberLong(1)
		},
		"appliedOpTime" : {
			"ts" : Timestamp(1616910574, 1),
			"t" : NumberLong(1)
		},
		"durableOpTime" : {
			"ts" : Timestamp(1616910574, 1),
			"t" : NumberLong(1)
		}
	},
	"lastStableCheckpointTimestamp" : Timestamp(1616910574, 1),
	"electionCandidateMetrics" : {
		"lastElectionReason" : "electionTimeout",
		"lastElectionDate" : ISODate("2021-03-28T05:36:42.092Z"),
		"electionTerm" : NumberLong(1),
		"lastCommittedOpTimeAtElection" : {
			"ts" : Timestamp(0, 0),
			"t" : NumberLong(-1)
		},
		"lastSeenOpTimeAtElection" : {
			"ts" : Timestamp(1616909801, 1),
			"t" : NumberLong(-1)
		},
		"numVotesNeeded" : 1,
		"priorityAtElection" : 1,
		"electionTimeoutMillis" : NumberLong(10000),
		"newTermStartDate" : ISODate("2021-03-28T05:36:42.112Z"),
		"wMajorityWriteAvailabilityDate" : ISODate("2021-03-28T05:36:42.220Z")
	},
	"members" : [
		{
			"_id" : 0,
			"name" : "172.18.87.20:27017",
			"health" : 1,
			"state" : 1,
			"stateStr" : "PRIMARY",
			"uptime" : 1002,
			"optime" : {
				"ts" : Timestamp(1616910574, 1),
				"t" : NumberLong(1)
			},
			"optimeDate" : ISODate("2021-03-28T05:49:34Z"),
			"syncingTo" : "",
			"syncSourceHost" : "",
			"syncSourceId" : -1,
			"infoMessage" : "",
			"electionTime" : Timestamp(1616909802, 1),
			"electionDate" : ISODate("2021-03-28T05:36:42Z"),
			"configVersion" : 3,
			"self" : true,
			"lastHeartbeatMessage" : ""
		},
		{
			"_id" : 1,
			"name" : "172.18.86.119:27017",
			"health" : 1,
			"state" : 2,
			"stateStr" : "SECONDARY",
			"uptime" : 9,
			"optime" : {
				"ts" : Timestamp(1616910574, 1),
				"t" : NumberLong(1)
			},
			"optimeDurable" : {
				"ts" : Timestamp(1616910574, 1),
				"t" : NumberLong(1)
			},
			"optimeDate" : ISODate("2021-03-28T05:49:34Z"),
			"optimeDurableDate" : ISODate("2021-03-28T05:49:34Z"),
			"lastHeartbeat" : ISODate("2021-03-28T05:49:42.055Z"),
			"lastHeartbeatRecv" : ISODate("2021-03-28T05:49:43.083Z"),
			"pingMs" : NumberLong(1),
			"lastHeartbeatMessage" : "",
			"syncingTo" : "",
			"syncSourceHost" : "",
			"syncSourceId" : -1,
			"infoMessage" : "",
			"configVersion" : 3
		}
	],
	"ok" : 1,
	"operationTime" : Timestamp(1616910574, 1),
	"$clusterTime" : {
		"clusterTime" : Timestamp(1616910574, 1),
		"signature" : {
			"hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
			"keyId" : NumberLong(0)
		}
	}
}

 

参数 描述
host 副本集成员地址,格式一般是ip:端口
arbiterOnly 可选值,当为true时则表示该节点是仲裁者

仲裁节点也可以使用该命令,还可以使用下面的命令添加仲裁节点

rs.addArb(host)
rs.addArb("172.18.86.227:27017")
myrs:PRIMARY> rs.addArb("172.18.86.227:27017")
{
	"ok" : 1,
	"operationTime" : Timestamp(1616910714, 1),
	"$clusterTime" : {
		"clusterTime" : Timestamp(1616910714, 1),
		"signature" : {
			"hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
			"keyId" : NumberLong(0)
		}
	}
}
myrs:PRIMARY> rs.status()
{
	"set" : "myrs",
	"date" : ISODate("2021-03-28T05:52:06.480Z"),
	"myState" : 1,
	"term" : NumberLong(1),
	"syncingTo" : "",
	"syncSourceHost" : "",
	"syncSourceId" : -1,
	"heartbeatIntervalMillis" : NumberLong(2000),
	"optimes" : {
		"lastCommittedOpTime" : {
			"ts" : Timestamp(1616910714, 1),
			"t" : NumberLong(1)
		},
		"readConcernMajorityOpTime" : {
			"ts" : Timestamp(1616910714, 1),
			"t" : NumberLong(1)
		},
		"appliedOpTime" : {
			"ts" : Timestamp(1616910714, 1),
			"t" : NumberLong(1)
		},
		"durableOpTime" : {
			"ts" : Timestamp(1616910714, 1),
			"t" : NumberLong(1)
		}
	},
	"lastStableCheckpointTimestamp" : Timestamp(1616910702, 1),
	"electionCandidateMetrics" : {
		"lastElectionReason" : "electionTimeout",
		"lastElectionDate" : ISODate("2021-03-28T05:36:42.092Z"),
		"electionTerm" : NumberLong(1),
		"lastCommittedOpTimeAtElection" : {
			"ts" : Timestamp(0, 0),
			"t" : NumberLong(-1)
		},
		"lastSeenOpTimeAtElection" : {
			"ts" : Timestamp(1616909801, 1),
			"t" : NumberLong(-1)
		},
		"numVotesNeeded" : 1,
		"priorityAtElection" : 1,
		"electionTimeoutMillis" : NumberLong(10000),
		"newTermStartDate" : ISODate("2021-03-28T05:36:42.112Z"),
		"wMajorityWriteAvailabilityDate" : ISODate("2021-03-28T05:36:42.220Z")
	},
	"members" : [
		{
			"_id" : 0,
			"name" : "172.18.87.20:27017",
			"health" : 1,
			"state" : 1,
			"stateStr" : "PRIMARY",
			"uptime" : 1145,
			"optime" : {
				"ts" : Timestamp(1616910714, 1),
				"t" : NumberLong(1)
			},
			"optimeDate" : ISODate("2021-03-28T05:51:54Z"),
			"syncingTo" : "",
			"syncSourceHost" : "",
			"syncSourceId" : -1,
			"infoMessage" : "",
			"electionTime" : Timestamp(1616909802, 1),
			"electionDate" : ISODate("2021-03-28T05:36:42Z"),
			"configVersion" : 4,
			"self" : true,
			"lastHeartbeatMessage" : ""
		},
		{
			"_id" : 1,
			"name" : "172.18.86.119:27017",
			"health" : 1,
			"state" : 2,
			"stateStr" : "SECONDARY",
			"uptime" : 152,
			"optime" : {
				"ts" : Timestamp(1616910714, 1),
				"t" : NumberLong(1)
			},
			"optimeDurable" : {
				"ts" : Timestamp(1616910714, 1),
				"t" : NumberLong(1)
			},
			"optimeDate" : ISODate("2021-03-28T05:51:54Z"),
			"optimeDurableDate" : ISODate("2021-03-28T05:51:54Z"),
			"lastHeartbeat" : ISODate("2021-03-28T05:52:04.895Z"),
			"lastHeartbeatRecv" : ISODate("2021-03-28T05:52:06.449Z"),
			"pingMs" : NumberLong(0),
			"lastHeartbeatMessage" : "",
			"syncingTo" : "",
			"syncSourceHost" : "",
			"syncSourceId" : -1,
			"infoMessage" : "",
			"configVersion" : 4
		},
		{
			"_id" : 2,
			"name" : "172.18.86.227:27017",
			"health" : 1,
			"state" : 7,
			"stateStr" : "ARBITER",
			"uptime" : 11,
			"lastHeartbeat" : ISODate("2021-03-28T05:52:04.907Z"),
			"lastHeartbeatRecv" : ISODate("2021-03-28T05:52:04.947Z"),
			"pingMs" : NumberLong(1),
			"lastHeartbeatMessage" : "",
			"syncingTo" : "",
			"syncSourceHost" : "",
			"syncSourceId" : -1,
			"infoMessage" : "",
			"configVersion" : 4
		}
	],
	"ok" : 1,
	"operationTime" : Timestamp(1616910714, 1),
	"$clusterTime" : {
		"clusterTime" : Timestamp(1616910714, 1),
		"signature" : {
			"hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
			"keyId" : NumberLong(0)
		}
	}
}
myrs:PRIMARY> 

 添加了的副本可以使用 rs.remove(host) 移除

 

 

 

 

 

 

上一篇:MongoDB副本集版本升级


下一篇:mongodb搭建Replica Set