如何使用FluentDocker连接到mongodb



我试图使用FluentDocker运行对MongoDB的测试,但我无法连接到它,见下面的代码。

[Fact]
public async Task TestMongoDbConnection3()
{
const string root = "root";
const string secret = "secret";

using (
var container =
new Builder().UseContainer()
.UseImage("mongo")
.WithEnvironment($"MONGO_INITDB_ROOT_USERNAME:{root}")
.WithEnvironment($"MONGO_INITDB_ROOT_PASSWORD:{secret}")
.ExposePort(27018)
.WaitForPort("27018/tcp", 30000 /*30s*/)
.Build()
.Start())
{
var config = container.GetConfiguration(true);
Assert.Equal(ServiceRunningState.Running, config.State.ToServiceState());

const string connectionString = "mongodb://root:secret@localhost:27018";
// insert data 
const string collectionName = "Users";

var mongoClient = new MongoClient(connectionString);
var database = mongoClient.GetDatabase ("Users");
var collection = database.GetCollection<User>(collectionName);

const int id = 1;
var data = new Fixture().Build<User>()
.With(x => x.Id, id)
.Create();
// delete if exists, but got timeout after 30000 ms
await collection.DeleteOneAsync(x => x.Id == data.Id);

...
}
}

我试图从配置(config. networksettings . ipaddress)中替换本地主机的IP,但仍然得到超时。

任何想法?

许多谢谢,

这是var ep = container.ToHostExposedEndpoint("27017/tcp");的修复程序,可以在我的macos上本地运行。

是完整的代码。当它在docker-in-docker镜像上运行时,它仍然会下降(超时)。

[Fact]
public void Test_Run_PingCommand_returns_True()
{
const string root = "root";
const string secret = "secret";
using (
var container =
new Builder().UseContainer()
.UseImage("mongo")
.WithEnvironment(new []{$"MONGO_INITDB_ROOT_USERNAME={root}",
$"MONGO_INITDB_ROOT_PASSWORD={secret}"})
.ExposePort(27017)
.WaitForPort("27017/tcp", 30000 /*30s*/)
.Build()
.Start())
{
var config = container.GetConfiguration(true);
Assert.Equal(ServiceRunningState.Running, config.State.ToServiceState());

var ep = container.ToHostExposedEndpoint("27017/tcp");

var connectionString =
$"mongodb://{root}:{secret}@{ep}";

var setting = new UsageDbSettings();
var mongoClient = new MongoClient(connectionString);
var database = mongoClient.GetDatabase(setting.DatabaseName);

var isMongoLive = database.RunCommandAsync((Command<BsonDocument>)"{ping:1}").Wait(30000);

Assert.True(isMongoLive);
}
}

相关内容

  • 没有找到相关文章

最新更新