Docker Compose部署Mongodb副本集群教程
version: '3.7'
services:
mongo-primary:
image: mongo:4.2
ports:
- "27017:27017"
environment:
MONGO_INITDB_ROOT_USERNAME: rootuser
MONGO_INITDB_ROOT_PASSWORD: rootpass
command: mongod --replSet "rs0" --bind_ip_all
mongo-secondary:
image: mongo:4.2
depends_on:
- mongo-primary
environment:
MONGO_INITDB_ROOT_USERNAME: rootuser
MONGO_INITDB_ROOT_PASSWORD: rootpass
command: >
sh -c '
until mongo --username rootuser --password rootpass --host mongo-primary --eval "printjson(rs.status())";
do
echo "MongoDB Primary is unavailable - sleeping"
sleep 1
done
mongo --username rootuser --password rootpass --host mongo-primary --eval "printjson(rs.initiate({_id: 'rs0', members: [{_id: 0, host: 'mongo-primary:27017'}, {_id: 1, host: 'mongo-secondary:27017'}]}))"
mongo --username rootuser --password rootpass --host mongo-primary --eval "while (rs.status().myState != 'SECONDARY') sleep(1000);"
'
mongo-arbiter:
image: mongo:4.2
depends_on:
- mongo-primary
- mongo-secondary
environment:
MONGO_INITDB_ROOT_USERNAME: rootuser
MONGO_INITDB_ROOT_PASSWORD: rootpass
command: >
sh -c '
until mongo --username rootuser --password rootpass --host mongo-primary --eval "printjson(rs.status())";
do
echo "MongoDB replica set is unavailable - sleeping"
sleep 1
done
mongo --username rootuser --password rootpass --host mongo-primary --eval "printjson(rs.addArb(\"mongo-arbiter:27017\"))"
'
这个示例代码展示了如何使用Docker Compose来部署一个具有一个主节点(mongo-primary),一个辅助节点(mongo-arbiter)和一个次要节点(mongo-secondary)的MongoDB副本集。每个服务都配置了相应的环境变量和命令,以确保副本集的正确初始化和运行。
评论已关闭