"Server Selection Timeout Error" MongoDB Go Driver with Docker

When you running the service and mongodb in docker you can't use localhost since the service is in a different container than mongodb, and from docker point of view it's under a different ip address.

You can connect with the service name you specify in docker-compose datastore

mongo.Connect("mongodb://datastore:27017")

Edit:

from: https://docs.docker.com/compose/networking/

By default Compose sets up a single network for your app. Each container for a service joins the default network and is both reachable by other containers on that network, and discoverable by them at a hostname identical to the container name

Meaning that if you run multiple containers via compose, you can access one container from the other by the container name,

Basically when docker-compose starts, it sets up the network, and each container in the compose joins the network under its container name. For a container's point if view, localhost is just the container itself, while he can search for other container's name and get back the container’s IP address.

Assuming that the docker is running on your localhost, you can set the name in etc/hosts file like this:

127.0.0.1 datastore

(if not just replace 127.0.0.1 with the docker ip)

And in the app you will connect with mongodb://datastore:27017

So you will be able to run the service both in the docker and from outside, if you'll decide to run only the db in docker

docker-compose start datastore

If you are connecting to one docker from another (like it is written in your docker-compose file, and using bridge network mode, you have to change your localhost to the hostname, like datastore

client, err := mongo.Connect("mongodb://datastore:27017")

When your go script uses localhost, it expects the database to located in the same docker

Tags:

Docker

Mongodb

Go