环境
Ubuntu 20.04 LTS
MongDB 5.0.3
说明
使用单机搭建 mongodb repliceset 三节点伪集群
步骤
安装
安装 mongodb,参考官方文档
1 2 3 4 5 6 7 8 9 10
| # wget -qO - https://www.mongodb.org/static/pgp/server-5.0.asc | sudo apt-key add - # echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/5.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-5.0.list # echo "deb [ arch=amd64,arm64 ] https://mirrors.aliyun.com/mongodb/apt/ubuntu focal/mongodb-org/5.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-5.0.list # sudo apt update # sudo apt install -y mongodb-org
|
创建目录
1
| sudo mkdir -p /opt/app/mongodb/{db1,db2,db3}/{data,etc,log}
|
配置文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| # db1: /opt/app/mongodb/db1/etc/mongodb.conf dbpath=/opt/app/mongodb/db1/data logpath=/opt/app/mongodb/db1/log/mongodb.log logappend=true journal=true bind_ip=0.0.0.0 port=27017
# db2: /opt/app/mongodb/db2/etc/mongodb.conf dbpath=/opt/app/mongodb/db2/data logpath=/opt/app/mongodb/db2/log/mongodb.log logappend=true journal=true bind_ip=0.0.0.0 port=27018
# db3: /opt/app/mongodb/db3/etc/mongodb.conf dbpath=/opt/app/mongodb/db3/data logpath=/opt/app/mongodb/db3/log/mongodb.log logappend=true journal=true bind_ip=0.0.0.0 port=27019
|
认证配置
启动服务
1 2 3
| sudo mongod -f /opt/app/mongodb/db1/etc/mongodb.conf --replSet rs & sudo mongod -f /opt/app/mongodb/db2/etc/mongodb.conf --replSet rs & sudo mongod -f /opt/app/mongodb/db3/etc/mongodb.conf --replSet rs &
|
登陆
1
| mongo --host localhost --port 27017
|
配置认证
1 2 3
| # > use admin > db.createUser({user: 'root', pwd: '123456', roles:[{role: 'userAdminAnyDatabase', db: 'admin'}, {role: 'readWriteAnyDatabase', db:'admin', {role: 'clusterAdmin', db:'admin'}}]})
|
keyfile配置
1 2 3 4 5 6 7
| # echo `openssl rand -base64 756` | sudo tee /opt/app/mongodb/keyfile sudo chmod 400 /opt/app/mongodb/keyfile
# auth=true keyfile=/opt/app/mongodb/keyfile
|
副本集配置
登陆其中一个节点
1
| mongo --host localhost --port 27017 -u root -p
|
配置副本集
1 2 3 4 5 6
| # > config = {_id: 'rs', members: [{_id: 0, host: 'localhost:27017'},{_id: 1, host: 'localhost:27018'},{_id: 2, host:'localhost:27019'}]} > rs.initiate(config)
# > rs.status()
|
修改副本集配置
1 2 3 4 5 6 7 8 9
| # 例: 修改node端口 # > cfg=rs.conf() # > cfg.members[0].host="localhost:27017" # > rs.reconfig(cfg) # > rs.reconfig(cfg, {force : true})
|