乐趣区

关于docker:Docker搭建mongodb主从结构

应用 docker 搭建一主二从的 replica set,并且保障 golang driver 能胜利连贯到该构造。
有如下目录构造:

.
├── config
│   └── config.sh
└── docker-compose.yml

其中 docker-compose.yml 文件内容如下:

version: "3.8"

services:

    mongo_setup:
        image: mongo:5.0.0
        hostname: mongo_setup
        container_name: mongo_setup
        volumes: 
            - ./config:/rs_config
        entrypoint: /usr/bin/bash /rs_config/config.sh
        restart: "no"
        networks:
            - mongo_net
        depends_on:
            - mongo1
            - mongo2
            - mongo3

    mongo1:
        image: mongo:5.0.0
        hostname: mongo1
        container_name: mongo1
        entrypoint: /usr/bin/mongod --port 27117 --replSet "rs0" --bind_ip_all
        ports: 
            - 27117:27117
        networks:
            - mongo_net
        restart: on-failure

    mongo2:
        image: mongo:5.0.0
        hostname: mongo2
        container_name: mongo2
        entrypoint: /usr/bin/mongod --port 27217 --replSet "rs0" --bind_ip_all
        ports: 
            - 27217:27217
        networks:
            - mongo_net
        restart: on-failure
        
    mongo3:
        image: mongo:5.0.0
        hostname: mongo3
        container_name: mongo3
        environment: 
            - RS_NAME=rs0
        entrypoint: /usr/bin/mongod --port 27317 --replSet "rs0" --bind_ip_all
        ports: 
            - 27317:27317
        networks:
            - mongo_net
        restart: on-failure


networks:
    mongo_net:

config.sh是用于配置主从的脚本,内容如下:

#/bin/bash

RS_NAME=rs0
MASTER=mongo1
REPLICA_1=mongo2
REPLICA_2=mongo3

until mongosh --host $MASTER --port 27117 --quiet <<EOF
exit
EOF
do
  sleep 5
done


mongosh --host $MASTER --port 27117 --quiet <<EOF
rs.initiate(
  {
     _id: "$RS_NAME",
     version: 1,
     members: [{ _id: 0, host : "${MASTER}:27117", priority: 2 },
        {_id: 1, host : "${REPLICA_1}:27217", priority: 1 },
        {_id: 2, host : "${REPLICA_2}:27317", priority: 1 }
     ]
  }
)
EOF

按如上配置,就能够应用 docker-compse up 启动该主从实例。
不过,如果在宿主机上应用 golang driver 来连贯该实例,会产生谬误,起因在于,连贯到 master 后,master 返回其余正本的信息,而后客户端尝试连贯其余正本,而因为宿主机与正本不在同一个网络里,因而无奈胜利通信。
解决的方法是配置宿主机的 host,利用 hosts 文件来帮忙宿主机解析其余正本的地址,减少上面几行:

# for mongodb replica
127.0.0.1  mongo1
127.0.0.1  mongo2
127.0.0.1  mongo3

OK.

退出移动版