Docker创建mongodb复制集


在docker搭建mongodb复制集合,用于提供数据冗余及高可用性,提供一定的容错能力,防止单个数据库丢失.

创建主节点

创建挂载目录并进入
mkdir -p /home/docker/test/node-p
cd /home/docker/test/node-p
创建数据挂载目录
mkdir db
生成mongodb-keyfile文件
openssl rand -base64 741 > mongodb-keyfile
设置文件权限
sudo chmod 600 mongodb-keyfile
sudo chown 999 mongodb-keyfile
启动主节点
docker run -d --name node-p -p 27027:27017 \
  -v /home/docker/test/node-p/db:/data/db \
  -v /home/docker/test/node-p/mongodb-keyfile:/opt/mongodb-keyfile \
  -v /etc/localtime:/etc/localtimmke:ro \
  --privileged=true \
  --restart=always \
  -e MONGO_INITDB_ROOT_USERNAME=root \
  -e MONGO_INITDB_ROOT_PASSWORD=mfweah0rGxyOH49A \
  mongo:4.2.6 --auth --keyFile /opt/mongodb-keyfile --oplogSize 102400 --wiredTigerCacheSizeGB 16 --replSet "cmdhelp" 
进入主节点容器
docker exec -it node-p /bin/bash
验证权限
mongo
use admin
db.auth('root','mfweah0rGxyOH49A')
初始化当前节点,配置权重为5
rs.initiate({ _id:"cmdhelp",members:[{_id:0,host:"192.168.2.234:27027", priority: 5}]})   

创建仲裁节点

创建挂载目录并进入
mkdir -p /home/docker/test/node-m
cd /home/docker/test/node-m
创建数据挂载目录
mkdir db
复制主节点mongodb-keyfile文件(根据自己的实际路径复制)
scp /home/docker/test/node-p/mongodb-keyfile .
设置文件权限
sudo chmod 600 mongodb-keyfile
sudo chown 999 mongodb-keyfile
启动仲裁节点
docker run -d --name node-m -p 27028:27017 \
  -v /home/docker/test/node-m/db:/data/db \
  -v /home/docker/test/node-m/mongodb-keyfile:/opt/mongodb-keyfile \
  -v /etc/localtime:/etc/localtimmke:ro \
  --privileged=true \
  --restart=always \
  -e MONGO_INITDB_ROOT_USERNAME=root \
  -e MONGO_INITDB_ROOT_PASSWORD=mfweah0rGxyOH49A \
  mongo:4.2.6 --auth --keyFile /opt/mongodb-keyfile --oplogSize 102400 --wiredTigerCacheSizeGB 1 --replSet "cmdhelp" 

创建从节点

创建挂载目录并进入
mkdir -p /home/docker/test/node-s
cd /home/docker/test/node-s
创建数据挂载目录
mkdir db
复制主节点mongodb-keyfile文件(根据自己的实际路径复制)
scp /home/docker/test/node-p/mongodb-keyfile .
设置文件权限
sudo chmod 600 mongodb-keyfile
sudo chown 999 mongodb-keyfile
启动从节点
docker run -d --name node-s -p 27029:27017 \
  -v /home/docker/test/node-s/db:/data/db \
  -v /home/docker/test/node-s/mongodb-keyfile:/opt/mongodb-keyfile \
  -v /etc/localtime:/etc/localtimmke:ro \
  --privileged=true \
  --restart=always \
  -e MONGO_INITDB_ROOT_USERNAME=root \
  -e MONGO_INITDB_ROOT_PASSWORD=mfweah0rGxyOH49A \
  mongo:4.2.6 --auth --keyFile /opt/mongodb-keyfile --oplogSize 102400 --wiredTigerCacheSizeGB 16 --replSet "cmdhelp" 

配置仲裁节点和从节点

进入主节点容器
docker exec -it node-p /bin/bash
管理权限验证
mongo
use admin
db.auth('root','mfweah0rGxyOH49A')
配置仲裁节点
rs.addArb("192.168.2.234:27028")
配置从节点
rs.add("192.168.2.234:27029")
查看节点状态
rs.status()
ps:
  •  mongodb-keyfile需要保持一直且需要配置权限
  •  本次测试在单机上,多机更换对应的ip即可
Was this helpful?

I hope to help every developer quickly find the commands they need. Of course, you can also add your own commonly used commands for easy searching.