在 docker 群中启动 MongoDB 副本集

Initiate MongoDB replica set in docker swarm

我在docker-[=中创建了两个配置服务器,副本集名称为rs0 50=] 文件部署为 sudo docker stack deploy --with-registry-auth --compose-file docker-compose.yml test.

version: "3.3"
services:
    cfg1-r1:
        image: mongo:3.2
        deploy:
            placement:
                constraints: [node.hostname == ram-ThinkPad-E470]
            restart_policy:
                condition: on-failure
        volumes:
            - /opt/mongoshard/tmp:/var/lib/mongodb
            - /opt/mongoshard/mongod.conf:/etc/mongod.conf
        networks:
            - mongoshard  
        command: ["mongod", "--configsvr", "--replSet", "rs0", "--dbpath", "/var/lib/mongodb", "--port", "27017"]

    cfg2-r1:
        image: mongo:3.2
        deploy:
            placement:
                constraints: [node.hostname == prasanna-ThinkPad-E470]
            restart_policy:
                condition: on-failure
        volumes:
            - /opt/mongoshard/tmp:/var/lib/mongodb
            - /opt/mongoshard/mongod.conf:/etc/mongod.conf
        networks:
            - mongoshard
        command: ["mongod", "--configsvr", "--replSet", "rs0", "--dbpath", "/var/lib/mongodb", "--port", "27017"]
networks:
    mongoshard:

mongod.conf 文件中的内容

storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true

systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log
net:
  port: 27017

当我尝试使用服务名称启动时

sudo docker exec -it $(sudo docker ps -qf label=com.docker.swarm.service.name=test_cfg1-r1) mongo --eval 'rs.initiate({ _id: "rs0", members: [{ _id: 1, host: "cfg1-r1:27017" }, { _id: 2, host: "cfg2-r1:27017" }], settings: { getLastErrorDefaults: { w: "majority", wtimeout: 30000 }}})'

编辑 我忘记在初始化时提到 cfg2-r1。现在我添加了它。

出现错误

MongoDB shell version v3.4.9
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.9
{
        "ok" : 0,
        "errmsg" : "No host described in new configuration 1 for replica set rs0 maps to this node",
        "code" : 93,
        "codeName" : "InvalidReplicaSetConfig"
}

编辑: 我认为问题是 cfg1-r1 和 cfg2-r2 服务不在同一个网络中。当我部署堆栈文件时,会创建一个名为 mongo_mongoshard(overlay) 的网络,当我检查它时,它在其容器列表中仅显示 cfg1-r1 作为容器。

您的网络必须处于覆盖模式,以允许多个主机之间共享专用网络:

docker network create --driver overlay --attachable mongoshard

然后在您的撰写中:

networks:
  mongoshard:
    external: true

为了复制作品,您需要至少添加两个成员:

rs.initiate({ _id: "rs0", members: [{ _id: 1, host: "cfg1-r1:27017" }, { _id: 2, host: "cfg1-r2:27017" }], settings: { getLastErrorDefaults: { w: "majority", wtimeout: 30000 }}});

driver: overlay 添加到 docker-compose.yml 文件中的 mongoshard: 网络:

networks:
  mongoshard:
    driver: overlay