skip to Main Content

I’m running a mongo image in a container with this config:

version: '3'
services:
  mongodb:
    image: mongo
    ports:
      - '27017:27017'
    environment:
      - MONGO_INITDB_ROOT_USERNAME=user
      - MONGO_INITDB_ROOT_PASSWORD=password
      - MONGO_INITDB_DATABASE=microservices
    volumes:
      - ./docker-entrypoint-initdb.d/mongo-init.js:/docker-entrypoint-initdb.d/mongo-init.js:ro

And I have started to build microservices with golang and I want to start dockerizing those as well to speed up the development process. However when I try to run this Dockerfile below it panics at the run test command with the error:

database url:  mongodb://user:[email protected]:27017/microservices
server selection error: server selection timeout, current topology: { Type: Unknown, Servers: [{ Addr: 127.0.0.1:27017, Type: Unknown, Last error: connection() error occurred during connection handshake: dial tcp 127.0.0.1:27017: connect: connection refused }, ] }

panic: server selection error: server selection timeout, current topology: { Type: Unknown, Servers: [{ Addr: 127.0.0.1:27017, Type: Unknown, Last error: connection() error occurred during connection handshake: dial tcp 127.0.0.1:27017: connect: connection refused }, ] }

The db connection works since when I try to run the test from the go files, they pass. There only seems to be any problem when I try to run them from the container when building it up.

FROM golang:1.18 as build

WORKDIR /go/src/app
COPY . .

RUN go mod download
RUN go vet -v /go/src/app/...
RUN go test -v /go/src/app/...

RUN CGO_ENABLED=0 go build -o /go/bin/app/authsvc /go/src/app/authentication/main.go

FROM gcr.io/distroless/static-debian11

COPY --from=build /go/bin/app/authsvc /
COPY --from=build /go/src/app/authentication/.env /
CMD ["/authsvc"]

2

Answers


  1. Change database url

    try mongodb

    database url:  mongodb://user:password@mongodb:27017/microservices
    
    Login or Signup to reply.
  2. So first of all you must check your default network ip with

    docker network ls
    

    Result

    After get network id and use this command :

    docker inspect <your network id>
    

    Inside result schema get your Gateway ip

    "IPAM": {
        "Driver": "default",
        "Options": null,
        "Config": [
            {
                "Subnet": "111.11.0.0/11",
                "Gateway": "111.11.0.1"
            }
        ]
    }
    

    and use that ip

    database url:  mongodb://user:password@ < your Gateway ip > :27017/microservices
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search