简体   繁体   中英

Go mgo.v2 package error: no reachable servers

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM