Need help with mongoDB go driver

Hi All,

I am using official mongoDB go driver in my code and it was working fine until I decided to use docker-compose to spin up my mongodb and go-app container.

My code builds fine but I am getting below error whenever I try to access home page of my go web-app.


app        | 2020/07/14 13:19:00 server selection error: server selection timeout, current topology: { Type: Unknown, Servers: [{ Addr: localhost:27017, Type: Unknown, State: Connected, Average RTT: 0, Last error: connection() : dial tcp connect: connection refused }, ] }

Docker-Compose File:

version: '3.1'


    image: mongo
    container_name: mongodb
    restart: always
          - 27017:27017
    command: mongod --bind_ip mongodb

    image: app:1.4
    container_name: app
      - MONGO_URL=mongodb
         - 80:8080
      - mongodb
    restart: always

Running Docker Containers

docker ps
CONTAINER ID        IMAGE                COMMAND                  CREATED             STATUS              PORTS                      NAMES
d130336be71e        app:1.4   "/app/main"              4 minutes ago       Up 2 seconds>8080/tcp       app
dc57dd2de645        mongo                "docker-entrypoint.s…"   4 minutes ago       Up 2 seconds>27017/tcp   mongodb


func GetSession() (*mongo.Client, error) {
	dbURL := os.Getenv("MONGO_URL")
	// Set client options
	clientOptions := options.Client()
	clientOptions.SetDirect(true).ApplyURI("mongodb://" + dbUser + ":" + dbPassword + "@" + dbURL +":27017/?connect=direct")

	// Connect to MongoDB
	client, err := mongo.Connect(context.TODO(), clientOptions)

	if err != nil {
		Logger(Fatal, err)

	// Check the connection
	err = client.Ping(context.TODO(), nil)

	if err != nil {
		Logger(Fatal, err)
	// Return successful connection
	return client, nil



  1. As part of trying to figure out what is wrong I looked at similar issues highlighted in stackoverflow and tried below options:
  • Tried to use connect=direct in connection URI
  • Tried to use SetDirect
  • Added --bindip as highlighted in my docker-compose file
  1. I logged-in into the app container and tried to ping mongodb and it worked:
root@d130336be71e:/app# ping mongodb
PING mongodb ( 56(84) bytes of data.
64 bytes from mongodb.app_default ( icmp_seq=1 ttl=64 time=0.159 ms
64 bytes from mongodb.app_default ( icmp_seq=2 ttl=64 time=0.200 ms
64 bytes from mongodb.app_default ( icmp_seq=3 ttl=64 time=0.079 ms
64 bytes from mongodb.app_default ( icmp_seq=4 ttl=64 time=0.087 ms
64 bytes from mongodb.app_default ( icmp_seq=5 ttl=64 time=0.083 ms
--- mongodb ping statistics ---
5 packets transmitted, 5 received, 0% packet loss, time 60ms
rtt min/avg/max/mdev = 0.079/0.121/0.200/0.050 ms

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.