我应该为mongodb集群配置两个节点。每个节点都应该复制所有数据。如果一个服务器死了,那么另一个应该假定为主服务器。
在我配置集群之前,我正在使用Docker实例进行本地测试来配置它。
As I saw in the documentation
,我应该至少有3个MongoDB实例。是这样吗?
首先我用docker创建了树实例,我将实例一配置为主实例。下面的代码是我的docker编写和配置脚本。
码头工人组成:
version: '3'
services:
mongo-2:
container_name: mongo-2
image: mongo:4
ports:
- 30102:27017
command: mongod --replSet cnf-serv --port 27017 --oplogSize 16 --bind_ip_all
restart: always
mongo-3:
container_name: mongo-3
image: mongo:4
ports:
- 30103:27017
command: mongod --replSet cnf-serv --port 27017 --oplogSize 16 --bind_ip_all
restart: always
mongo-1:
container_name: mongo-1
image: mongo:4
ports:
- 30101:27017
command: mongod --replSet cnf-serv --port 27017 --oplogSize 16 --bind_ip_all
links:
- mongo-2:mongo-2
- mongo-3:mongo-3
restart: always
mongo-setup:
container_name: mongo-setup
image: mongo:4
depends_on:
- mongo-1
- mongo-2
- mongo-3
links:
- mongo-1:mongo-1
- mongo-2:mongo-2
- mongo-3:mongo-3
volumes:
- ./scripts:/scripts
environment:
- MONGO1=mongo-1
- MONGO2=mongo-2
- MONGO3=mongo-3
- RS=cnf-serv
- PORT=27017
entrypoint: [ "/scripts/setup.sh" ]
配置脚本:
#!/bin/bash
mongodb1=`getent hosts ${MONGO1} | awk '{ print $1 }'`
mongodb2=`getent hosts ${MONGO2} | awk '{ print $1 }'`
mongodb3=`getent hosts ${MONGO3} | awk '{ print $1 }'`
port=${PORT:-27017}
echo "Waiting for startup.."
until mongo --host ${mongodb1}:${port} --eval 'quit(db.runCommand({ ping: 1 }).ok ? 0 : 2)' &>/dev/null; do
printf '.'
sleep 1
done
echo "Started.."
echo setup.sh time now: `date +"%T" `
mongo --host ${mongodb1}:${port} <<EOF
var cfg = {
"_id": "${RS}",
"protocolVersion": 1,
"members": [
{
"_id": 100,
"host": "${mongodb1}:${port}"
},
{
"_id": 101,
"host": "${mongodb2}:${port}"
},
{
"_id": 102,
"host": "${mongodb3}:${port}"
}
]
};
rs.initiate(cfg, { force: true });
rs.reconfig(cfg, { force: true });
EOF
当我尝试在任何外部容器端口中连接时,都会收到相同的错误消息:
Could not connect to MongoDB on the provided host and port
如何使用DOCKER配置内部集群?