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.
I have tried:
- Exposing/publishing ports, so I can use the container name instead of 'mongodb:localhost:27017/' when trying to connect to the client.
- I have also removed any network config in my compose.yml file so that there is no network confusion.
This is my compose.yml file:
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
This is my mongo_todo Dockerfile:
FROM golang:1.14
WORKDIR /go/src/app
COPY . .
RUN go get -d -v ./...
RUN go install -v ./...
EXPOSE 80
And this is how I am trying to connect to the client:
// Set client options
clientOptions := options.Client().ApplyURI("mongodb://mongodb:27017")
// Connect to MongoDB
Client, _ = mongo.Connect(context.TODO(), clientOptions)
// Check the connection
err := Client.Ping(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
The program is logging a Fatal error when trying to ping the client to check the connection.
Log output:
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
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.
Please ask me for more information if needed and thanks in advance for any help.
Edit: I can ping the hostname mongodb from my go_todo container so not sure if it is a network issue.