skip to Main Content

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.

3

Answers


  1. 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.

    Login or Signup to reply.
  2. 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)
    
    Login or Signup to reply.
  3. I was facing the same issue and this command did the trick for me, was mentioned here.

    Docker provides a host network which lets containers share your host’s networking stack. This approach means localhost inside a container resolves to the physical host, instead of the container itself.

    docker run -d --network=host my-container:latest
    

    hope it help someone.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search