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

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.

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

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题