docker搭建3个实例mongodb(6.0)副本集

1、查看mongodb镜像:

docker search mongo;

docker搭建3个实例mongodb(6.0)副本集_第1张图片

2、拉取mongodb镜像:

docker pull mongo;

 docker搭建3个实例mongodb(6.0)副本集_第2张图片

3、创建目录,分别保存3个mongodb实例数据、备份、秘钥:

mkdir -p /usr/local/mongo/mongo-rs/{data01,data02,data03,key,backup};

4、 切换至创建的目录下:

cd /usr/local/mongo/mongo-rs/;
openssl rand -base64 756 > key/mongo-rs.key;
chmod 400 key/mongo-rs.key;
chown polkitd:input key/mongo-rs.key;

docker搭建3个实例mongodb(6.0)副本集_第3张图片

5、 创建3个mongodb节点:

docker run --name mongo-rs01 -p 27017:27017 -v /usr/local/mongo/mongo-rs/data01:/data/db -v /usr/local/mongo/mongo-rs/backup:/data/backup -v /usr/local/mongo/mongo-rs/key:/data/key -v /etc/localtime:/etc/localtime -e MONGO_INITDB_ROOT_USERNAME=admin -e MONGO_INITDB_ROOT_PASSWORD=123456 -d mongo:latest --replSet mongo-rs --auth --keyFile /data/key/mongo-rs.key --bind_ip_all;
docker run --name mongo-rs02 -p 27018:27017 -v /usr/local/mongo/mongo-rs/data02:/data/db -v /usr/local/mongo/mongo-rs/backup:/data/backup -v /usr/local/mongo/mongo-rs/key:/data/key -v /etc/localtime:/etc/localtime -e MONGO_INITDB_ROOT_USERNAME=admin -e MONGO_INITDB_ROOT_PASSWORD=123456 -d mongo:latest --replSet mongo-rs --auth --keyFile /data/key/mongo-rs.key --bind_ip_all;
docker run --name mongo-rs03 -p 27019:27017 -v /usr/local/mongo/mongo-rs/data03:/data/db -v /usr/local/mongo/mongo-rs/backup:/data/backup -v /usr/local/mongo/mongo-rs/key:/data/key -v /etc/localtime:/etc/localtime -e MONGO_INITDB_ROOT_USERNAME=admin -e MONGO_INITDB_ROOT_PASSWORD=123456 -d mongo:latest --replSet mongo-rs --auth --keyFile /data/key/mongo-rs.key --bind_ip_all;

6、进入任意节点,配置mongodb副本集:

docker exec -it mongo-rs01 bash;
mongosh;
use admin;
db.auth("admin","123456");
var config={
     "_id":"mongo-rs",
     "members":[
         {"_id":0,host:"192.168.1.38:27017"},
         {"_id":1,host:"192.168.1.38:27018"},
		 {"_id":2,host:"192.168.1.38:27019",arbiterOnly:true}
]};
rs.initiate(config);

docker搭建3个实例mongodb(6.0)副本集_第4张图片
mongdb客户端命令:6.0为mongosh,6.0以下为mongo
arbiterOnly:true 表示该节点为仲裁节点,只负责投票,不负责存储数据
执行rs.initiate()方法,初始化副本集,同时执行该方法的节点为主节点

7、查看副本集节点状态:

rs.status();

docker搭建3个实例mongodb(6.0)副本集_第5张图片

8、验证数据同步,在主节点插入数据:

use test;
db.test.insert({name:"mongodb rs test"});

docker搭建3个实例mongodb(6.0)副本集_第6张图片

 

9、在从节点查看数据:

docker exec -it mongo-rs02 bash;
mongosh;
use admin;
db.auth("admin","123456");
db.getMongo().setReadPref('secondary');
use test;
db.test.find();

docker搭建3个实例mongodb(6.0)副本集_第7张图片

你可能感兴趣的:(docker,镜像,后端,docker,mongodb,容器)