MongoDB Compass 立即断开连接

MongoDB Compass disconnects immediately

我正在尝试使用 MongoDB Compass 1.20.4

连接到 MongoDB

我的连接字符串是:

mongodb://localhost:27017/?replicaSet=rs0

这是我的 MongoDB docker 设置:

version: '3'
services:
  mongo0:
    hostname: mongo0
    container_name: mongo0
    image: mongo
    ports:
      - 27017:27017
    restart: always
    entrypoint: [ "/usr/bin/mongod", "--bind_ip_all", "--replSet", "rs0" ]
  mongo1:
    hostname: mongo1
    container_name: mongo1
    image: mongo
    ports:
      - 27018:27017
    restart: always
    entrypoint: [ "/usr/bin/mongod", "--bind_ip_all", "--replSet", "rs0" ]
  mongosetup:
    hostname: mongosetup
    container_name: mongosetup
    image: mongo
    depends_on:
      - mongo0
      - mongo1
    volumes:
      - ./scripts/:/scripts
    restart: "no"
    entrypoint: [ "bash", "/scripts/mongo-setup.sh" ]

mongo-setup.sh

#!/bin/bash
sleep 10
mongo --host mongo0:27017 <<EOF
  var config={"_id":"rs0","members":[{"_id":0,"host":"mongo0:27017"},{"_id":1,"host":"mongo1:27017"}]};
  rs.initiate(config);
EOF

这是我在 docker 日志中看到的内容:

mongo0            | 2020-02-02T14:42:35.114+0000 I  NETWORK  [listener] connection accepted from 172.27.0.1:55494 #31 (4 connections now open)
mongo0            | 2020-02-02T14:42:35.115+0000 I  NETWORK  [conn31] received client metadata from 172.27.0.1:55494 conn31: { driver: { name: "nodejs", version: "3.4.0" }, os: { type: "Darwin", name: "darwin", architecture: "x64", version: "19.3.0" }, platform: "'Node.js v10.2.0, LE (unified)", application: { name: "MongoDB Compass" } }
mongo0            | 2020-02-02T14:42:35.120+0000 I  NETWORK  [conn31] end connection 172.27.0.1:55494 (3 connections now open)

在使用副本集之前,它连接得很好,Studio 3T 也可以完美地使用此设置。非常感谢任何帮助

  1. 将 MongoDB Compass 中的 Read Preference 更改为 Primary Preferred 修复了连接问题。
  2. 然后我注意到我无法从 GUI modify/delete 进行任何操作,基本上我是通过只读模式连接的。在仔细查看 MongoDB 日志后,我注意到我的 PRIMARY 集在端口 27018 可用,而不是我连接到的 27017。

我调整了我的 mongo-setup.sh 以始终在端口 27017 设置 PRIMARY(设置优先级选项):

#!/bin/bash
# https://docs.mongodb.com/manual/tutorial/force-member-to-be-primary/
sleep 10
mongo --host mongo0:27017 <<EOF
  var config={"_id":"rs0","members":[{"_id":0,"host":"mongo0:27017","priority":1},{"_id":1,"host":"mongo1:27017", "priority":0.5}]};
  rs.initiate(config);
EOF
echo 'Finished mongo setup'

参考链接:
Replica Set Elections

Force a Member to Become Primary