5
I am creating a microservice in Go, using Mongodb as a database and using the library mgo
.
Using Mongodb in a Docker container locally and running the application on my machine, everything works normally, but when I tried to run using a Docker Compose file I could not make the connection between Go and Mongodb
The Dockerfile used to generate the image:
FROM golang:1.9.2 as builder
WORKDIR /app
RUN go get -u gopkg.in/mgo.v2
RUN go get -u github.com/gin-gonic/gin
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -o microservice .
FROM alpine:latest
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=builder /app/microservice .
EXPOSE 8080
CMD ["./microservice"]
The code of the Docker-Compose:
version: '3'
services:
api-user:
image: "api-user"
links:
- "mongodb"
environment:
- MONGO_URL="mongodb"
depends_on:
- mongodb
mongodb:
image: "mongo"
This is the code that makes the connection in Go:
session, err := mgo.Dial(os.Getenv("MONGO_URL"))
if err != nil {
panic(err)
}
The error launched by Go:
panic: no reachable servers
Running the ping in the microservice container, Mongodb returns confirming that there is a connection between the containers.
I have tried using the connection string from mongodb documentation and yet I was unsuccessful
I believe your problem is with Docker and not with the go itself. I am in doubt in those quotes on the value of the Environment key. That
links
in Docker Compose seems unnecessary to me too.– navossoc