I'm connecting to remote mongo server using following ssh tunneling command:
ssh -i document-db-tun.pem -L 27017:docdb-2019-07-30-09-40-47.cluster-cffrhwfhhfof.us-east-2.docdb.amazonaws.com:27017 ubuntu@ec2-3-19-68-147.us-east-2.compute.amazonaws.com -N
Also connecting to mongo server works fine using mongo command locally.
But when I'm trying to connect to it locally using golang code it throws Mongo connection ckeck failed. Err: context deadline exceeded
error.
const (
mongoTimeout = time.Second * 10
)
func initMongo() {
mongoConf := common.Conf.ServiceConfig.Databases.Mongo
ctx, _ := context.WithTimeout(context.Background(), mongoTimeout)
uri := fmt.Sprintf("mongodb://127.0.0.1:27017")
if common.IsSentryEnabled() {
sentry.AddBreadcrumb(&sentry.Breadcrumb{
Message: fmt.Sprintf("Connecting to mongo server at: '%v'", uri),
Category: common.SENTRY_CAT_REPO,
Level: sentry.LevelInfo,
})
}
client := options.Client().
SetReadPreference(readpref.SecondaryPreferred()).
SetAppName("catalog").
SetMaxConnIdleTime(time.Microsecond * 100000).
SetAuth(options.Credential{
Username: mongoConf.Username,
Password: mongoConf.Password,
}).
ApplyURI(uri)
pureMongoClient, err := mongo.Connect(ctx, client)
if err != nil {
if common.IsSentryEnabled() {
sentry.AddBreadcrumb(&sentry.Breadcrumb{
Message: "Error connecting to mongo",
Category: common.SENTRY_CAT_REPO,
Level: sentry.LevelFatal,
})
sentry.ConfigureScope(func(scope *sentry.Scope) {
scope.SetTags(map[string]string{
common.SENTRY_SCOPE_KEY: common.SENTRY_SCOPE_MONGO,
common.SENTRY_TYPE_KEY: common.SENTRY_TYPE_DB,
})
})
sentry.CaptureException(err)
sentry.Flush(time.Second * 5)
}
panic(fmt.Sprintf("Failed to establish mongo connection. Err: %v ", err))
}
err = pureMongoClient.Ping(ctx, readpref.Primary())
if err != nil {
if common.IsSentryEnabled() {
sentry.AddBreadcrumb(&sentry.Breadcrumb{
Message: "Mongo connection ckeck failed",
Category: common.SENTRY_CAT_REPO,
Level: sentry.LevelFatal,
})
sentry.ConfigureScope(func(scope *sentry.Scope) {
scope.SetTags(map[string]string{
common.SENTRY_SCOPE_KEY: common.SENTRY_SCOPE_MONGO,
common.SENTRY_TYPE_KEY: common.SENTRY_TYPE_DB,
})
})
sentry.CaptureException(err)
sentry.Flush(time.Second * 5)
}
panic(fmt.Sprintf("Mongo connection ckeck failed. Err: %v ", err))
}
mongoDB := pureMongoClient.Database(mongoConf.Dbname)
dbManager.MongoDB = &MGODatabase{
Database: mongoDB,
}
}
Username and Password used in the code are those which are required to connect to the remote server. What might be going wrong while connecting to the remote mongo server using golang code?