Reputation: 65
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:[email protected]: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
Upvotes: 1
Views: 2049
Reputation: 9980
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:[email protected]: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.
Upvotes: 1