I have a golang web app that use mongodb. I create two containers: one for my_app and the other for mongodb. I use the official mongo-go-driver/mongo.
var client *mongo.Client
//create a mongo.Client
client, err = mongo.NewClient("mongodb://localhost:27017")
//client, err = mongo.NewClient("mongodb://my_first_mongodb:27017")
//client, err = mongo.NewClient("mongodb://:27017")
if err != nil {
log.Printf("could not create a mongo client: %v", err)
panic(err)
}
//connect it to your running MongoDB server
ctx1, cancel1 := context.WithTimeout(context.Background(), 120*time.Second)
defer cancel1()
//Connect initializes the Client by starting background monitoring goroutines.
err = client.Connect(ctx1)
if err != nil {
log.Printf("could not connect with mongodb: %v", err)
panic(err)
}
fmt.Println("trying to start mongodb for my app")
ctx2, cancel2 := context.WithTimeout(context.Background(), 120*time.Second)
defer cancel2()
err = client.Ping(ctx2, nil)
if err != nil {
log.Printf("no ping to mongo db could not connect with mongodb: %v", err)
panic(err)
}
My problem is that I don't know how get(connect) the address ip (localhost) of mongodb inside a container. if I use
client, err = mongo.NewClient("mongodb://localhost:27017")
doesn't work. but if inside a docker-compose I set the container name (my_first_mongodb) and I use this code:
client, err = mongo.NewClient("mongodb://my_first_mongodb:27017")
is all fine and it is working.
The problem with this solution is that: Because Docker container names must be unique, you cannot scale a service beyond 1 container if you have specified a custom name. Attempting to do so results in an error here.
Any help please. Thanks