title: Go mongo-driver cannot connect to mongodb container
body: <p>I am using a simple go CRUD api that uses MongoDB and moving it to docker containers. I cannot connect to the MongoDB for some reason. After researching I cannot find a solution.</p>
  <p>I have tried:</p>
  <ul>
  <li>Exposing/publishing ports, so I can use the container name instead of 'mongodb:localhost:27017/' when trying to connect to the client.</li>
  <li>I have also removed any network config in my compose.yml file so that there is no network confusion.</li>
  </ul>
  <p>This is my compose.yml file:</p>
  <pre><code>version: '3.4'
      
  services:
      mongodb:
        image: mongo:4.0.4
        restart: always
        ports:
          - 27017:27017
        
      mongo_todo:
        build: ./mongo_todo
        ports: 
          - 3000:3000
        depends_on:
          - mongodb
        
      go_todo:
      build: ./go_todo
      ports:
        - 80:80
      depends_on:
        - mongo_todo
  </code></pre>
  <p>This is my mongo_todo Dockerfile:</p>
  <pre><code>FROM golang:1.14
  WORKDIR /go/src/app
  COPY . .
  
  RUN go get -d -v ./...
  RUN go install -v ./...
  
  EXPOSE 80
  </code></pre>
  <p>And this is how I am trying to connect to the client:</p>
  <pre><code>// Set client options
  clientOptions := options.Client().ApplyURI(&quot;mongodb://mongodb:27017&quot;)
  
  // Connect to MongoDB
  Client, _ = mongo.Connect(context.TODO(), clientOptions)
  
  // Check the connection
  err := Client.Ping(context.TODO(), nil)
  if err != nil {
      log.Fatal(err)
  }
  </code></pre>
  <p>The program is logging a Fatal error when trying to ping the client to check the connection.</p>
  <p>Log output:</p>
  <pre><code>panic: runtime error: invalid memory address or nil pointer dereference
  [signal SIGSEGV: segmentation violation code=0x1 addr=0x2e0 pc=0x9a798c]
  goroutine 1 [running]:
  go.mongodb.org/mongo-driver/mongo.(*Client).Ping(0x0, 0xd61e20, 0xc000028030, 0x0, 0x1, 0x0)
  /go/src/go.mongodb.org/mongo-driver/mongo/client.go:229 +0x21c
  main.main()
  /go/src/app/main.go:30 +0x16f
  </code></pre>
  <p>I understand that it is some kind of networking issue but I have no idea why it is not working and I have a feeling that there's something simple that I am missing.</p>
  <p>Please ask me for more information if needed and thanks in advance for any help.</p>
  <p>Edit: I can ping the hostname mongodb from my go_todo container so not sure if it is a network issue.</p>