在docker swarm中启动MongoDB副本集

时间:2017-10-14 10:43:33

标签: mongodb docker-swarm docker-stack

我在 docker-compose.yml 文件中创建了两个配置服务器,副本集名称 rs0 ,部署为 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:& #34; rs0",成员:[{_ id:1,主持人:" cfg1-r1:27017"},{_ id:2,主持人:" cfg2-r1:27017&#34 ;}],设置:{getLastErrorDefaults:{w:"多数",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作为其容器列表中的容器。

2 个答案:

答案 0 :(得分:1)

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

networks:
  mongoshard:
    driver: overlay

答案 1 :(得分:0)

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

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 }}});