I've followed the instructions in https://tsmx.net/docker-local-mongodb/ but I still get the following error:
**panic: unable to connect to MongoDB (local): no reachable servers **
I even tried the following but still get the same error:
_ = pflag.String("mongodb-addr", "127.0.0.1:27017", "MongoDB connection address")
My connection code is as follows:
dbAddr := d.cfg.GetString("mongodb-addr")
session, err := mgo.Dial(dbAddr)
And my docker run command is as follows:
docker run image_name
I'm using macOS Monterey. Any help would be greatly appreciated. Thanks.
CodePudding user response:
If the application and the MongoDB are on the same docker network, then use the docker name to connect to the MongoDB container.
If the MongoDB is running in the server where the application is running in docker container, then use the IP of the server to communicate to the MongoDB. 127.0.0.1
from within the container will try to find the MongoDB within the same Docker as the application.
CodePudding user response:
if you run mongo like this :
mongo:
image: mongo
restart: always
volumes:
- ./mongo-data:/data/db
env_file: .env
ports:
- 27017:27017
environment:
MONGO_INITDB_ROOT_USERNAME: ${MONGO_USERNAME}
MONGO_INITDB_ROOT_PASSWORD: ${MONGO_PASSWORD}
then you can connect from Go like this :
var cred options.Credential
cred.Username = MongoUsername
cred.Password = MongoPassword
clientOption := options.Client().ApplyURI(mongodb://mongodb:27017).SetAuth(cred)