CentOS7 安装 MongoDB 4.2 副本集
安装环境
系统版本:CentOS Linux release 7
mongoDB版本:mongoDB 4.2
节点信息
|
ip | 备注 |
主节点 | 172.0.0.1 | |
从节点 | 172.0.0.2 | |
仲裁节点 | 172.0.0.3 |
目录结构
数据路径:/mongo/db
日志路径:/mongo/log
密钥路径:/mongo/keyfile
安装方式
一 通过yum安装mongoDB如下
# moongoDb 库 /etc/yum.repos.d/mongodb-org-4.2.repo # yum安装 yum install -y mongodb-org
二、副本集 目录结构准备
# 目录及权限设置 mkdir -p /var/lib/mongo mkdir -p /var/log/mongodb chown -R mongod:mongod /var/lib/mongo chown -R mongod:mongod /var/log/mongodb # 目录及权限设置 mkdir /mongo/db mkdir /mongo/keyfile mkdir /mongo/log chown -R mongod:mongod /mongo # 生成kefile # 用于各节点之间安全认证 openssl rand -base64 700 > /mongo/keyfile/mongodb-keyfile chmod 500 /mongo/keyfile/mongodb-keyfile # 拷贝keyfile 到从服务器和仲裁节点 scp mongodb-keyfile mongo_user@192.168.0.2:/mongo/keyfile/ scp mongodb-keyfile mongo_user@192.168.0.3:/mongo/keyfile/
三、配置文件
三台服务器配置文件内容一致
# 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: /mongo/log/mongod.log
# Where and how to store data.
storage:
dbPath: /mongo/db
journal:
enabled: true
# engine:
# wiredTiger:
# how the process runs
processManagement:
fork: true # fork and run in background
pidFilePath: /var/run/mongodb/mongod.pid # location of pidfile
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:
security:
keyFile: /mongo/keyfile/mongodb-keyfile
authorization: enabled
#operationProfiling:
#replication:
replication:
replSetName: replica_id
#sharding:
## Enterprise-Only Options
#auditLog:
#snmp:
四、 启动服务
# 启动mongodb
systemctl start mongod.service
五、 配置副本集
# 在主库添加副本集信息 # 登陆数据库 mongo # 配置副本集replica_id ,名字可以自定义,但需要和配置文件保持一致 config={"_id":"replica_id",members:[ {_id:0,host:"172.0.0.1:27017"}, {_id:1,host:"172.0.0.2:27017"}, {_id:2,host:"172.0.0.3:27017",arbiterOnly:true} ] } # 初始化副本集:使用前面定义的replica_id rs.initiate(config) # 查询副本集状态 rs.status() # 副本集状态主要内容如下 172.168.0.1 "stateStr": "PRIMARY" 172.168.0.2 "stateStr": "SECONDARY" 172.168.0.3 "stateStr": "ARBITER"
常用维护指令
1. 新建管理员账户 # 登陆 mongo # 切换admin 数据库 use admin # 新建管理员root db.createUser( { user: "root", pwd: "password", roles: [ { role: "root", db: "admin" } ] })
# 数据库bussines新建普通(读写权限)用户rouser db.createUser( { user: "ro_user", pwd: "password", roles: [ { role: "readWrite", db: "bussiness" } ] })
# 修改密码 db.changeUserPassword("root", "newpassword") 2. 通过密码登陆mongo mongo --port 27017 -u root -p --authenticationDatabase admin 3. 备份数据库 mongodump -u root -p passowrd --authenticationDatabase admin -d dbname -o /bak/dbname 4. 还原数据库 mongorestore -uroot -p passowrd -d dbname /bak/dbname --authenticationDatabase admin