30000毫秒后C#Docker MongoDB超时

时间:2019-02-12 23:40:00

标签: c# mongodb docker

我对docker很陌生,并从中运行mongo。但是,当我想写它时遇到以下错误。当我纯粹在本地环境中使用mongo时(即在本地运行mongodb),这工作得很好。

我在docker-compose-test文件中引用mongo的方式如下:

  mongo:
    image: mongo
    restart: always
    ports:
      - 27017:27017    
    environment:
      MONGO_INITDB_ROOT_USERNAME: username
      MONGO_INITDB_ROOT_PASSWORD: password

然后在我的appsettings.config文件中,按如下所示设置连接字符串:

"MongoConnectionString": "mongodb://username:password@localhost:27017"

要注意的一件事是,我非常肯定这确实会使用这些凭据启动它的一个实例,因为如果我尝试使用具有本地主机的Mongo罗盘管理员连接到它,并且当我的docker compose没有启动并运行时,相应的密码和用户名将无法连接,在运行时可以正常工作。

也就是说,在我的代码中,我如下引导了我的mongo上下文:

//Create mongo class map
            Mapper.CreateMaps();  

            string connectionString = configuration.GetValue<string>("ConnectionStrings:MongoConnectionString");
            string mongoDataBase = configuration.GetValue<string>("MongoDataBases:MongoDataBaseName");

            _client = new MongoClient(connectionString);
            _database = _client.GetDatabase(mongoDataBase);

然后我尝试将所需的数据插入到我的集合中(这是失败的地方),如下所示:

//GetTypedMongoCollection returns a IMongoCollection<T>

var collection = mongoContext.GetTypedMongoCollection<MyCollection>();  

错误消息是:

       A timeout occured after 30000ms selecting a server using CompositeServerSelector{ Selectors = MongoDB.Driver.MongoClient+AreSessionsSupportedServerSelector, LatencyLimitingServerSelector
{ AllowedLatencyRange = 00:00:00.0150000 } }. Client view of cluster state is { ClusterId : "1", ConnectionMode : "Automatic", Type : "Unknown", State : "Disconnected", 
Servers : [{ ServerId: "{ ClusterId : 1, EndPoint : "Unspecified/localhost:27017" }", EndPoint: "Unspecified/localhost:27017", State: "Disconnected", Type: "Unknown", HeartbeatException: "MongoDB.Driver.MongoConnectionException: An exception occurred while opening a connection to the server. ---> MongoDB.Driver.MongoAuthenticationException: Unable to authenticate using sasl protocol mechanism SCRAM-SHA-1. ---> MongoDB.Driver.MongoCommandException: Command saslStart failed: Authentication failed

我注意到它确实提到了“未指定”,这是我认为是问题所在,但是如果是,那么将我的连接字符串构建到mongo的正确方法是什么?据我了解如下:我们拥有CTX,我们调用GetDatabase来创建数据库(如果不存在),然后在调用GetCollection时创建一个数据库(如果它不存在)。我在哪里弄错了?

1 个答案:

答案 0 :(得分:0)

在使用Docker compose时,应使用“ mongo”(来自您的compose文件的容器的名称)而不是localhost。我刚刚开始工作。

来源:https://medium.com/@kahana.hagai/docker-compose-with-node-js-and-mongodb-dbdadab5ce0a

相关问题