dongwen4487 2018-10-20 07:40
浏览 271
已采纳

Go mgo.v2软件包错误:没有可访问的服务器

Trying to use the mgo.v2 package to connect to the mongodb server. I have started the server using:

mongod --auth

I am able to connect to the server using the terminal using:

$ mongo -u "username" -p "password" --authenticationDatabase "db"

But when I use:

mgo.Dial("mongodb://usernamer:password@127.0.0.1:27017/dbname")

It gives me an error saying {"error":"no reachable servers"}.

My docker-compose.yml file is as below

version: "2"
services:
  todo:
    build:
      context: .
      dockerfile: todo/Dockerfile
    restart: always
    volumes:
    - .:/go/src/prac
    container_name: todo
    ports:
    - 8800:8081
  mongodb:
    command: mongod --auth
    container_name: mongodb
    image: mongo:latest
    ports:
    - 27017:27017
  • 写回答

1条回答 默认 最新

  • dourang6858 2018-10-20 12:37
    关注

    The problem appears to be that you are trying to connect to 127.0.0.1. MongoDB is not in the same container, so this won't work.

    mgo.Dial("mongodb://usernamer:password@127.0.0.1:27017/dbname")
    

    You should instead be connecting to the MongoDB container you defined by using the name you chose.

    mgo.Dial("mongodb://usernamer:password@mongodb:27017/dbname")
    

    Docker Compose creates a network for your containers in which they can access each other using the names you have defined as hostnames. Note that you don't need to define ports for containers to reach each other; these are only needed to reach containers from outside Docker.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?