1

I was trying to run sudo docker-compose up to get my app running and connect to a localhost mongodb but I ran into this error

time="2021-12-28T08:31:54Z" level=fatal msg="server selection error: context deadline exceeded, current topology: { Type: Unknown, Servers: [{ Addr: host.docker.internal:27017, Type: Unknown, Last error: connection() error occured during connection handshake: dial tcp: lookup host.docker.internal: no such host }, ] }"

Initially, I tried to replace localhost with host.docker.internal instead to have the mongo uri connect with the docker network but it doesn't seem to be able find it. I'm on the latest version of docker too, so it's not a question of unsupported docker version.

docker-compose.yaml

version: '3.3'
services:
  app: 
    build: 
      context: .
      dockerfile: dockerfile
    ports: 
      - "8080:20717"
    restart: unless-stopped
    env_file: .env
    networks:
      - ext
      - int

networks:
 ext:
 int:
  internal: true

I previously had an extra_hosts part but replaced that with the networks portion.

    extra_hosts:
        - "host.docker.internal:127.0.0.1"

My .env file contains the URI and some other necessary variables for the app

DB_URI=mongodb://host.docker.internal:27017
CITY_DB=nht_cities
COL_USER=user
COL_CITY=city
USER_AUTH_TOKEN=50dbafa...

My app itself runs on port 8080

fmt.Println("Server running at port 8080")
log.Fatal(http.ListenAndServe(":8080", r)) // r being the router
Lazlo
  • 159
  • 1
  • 7
  • What is your host OS? Can you run the MongoDB instance inside a container as well? – David Maze Dec 28 '21 at 10:35
  • I use Linux (Zorin OS). How can I do that and why would it help? – Lazlo Dec 28 '21 at 12:52
  • 1
    You can add a container based on [the `mongo` image](https://hub.docker.com/_/mongo) to your `docker-compose.yml` file. If you do, then you can use that Compose service name as a host name, without trying to figure out how to call out of Docker back to the host. See also [Networking in Compose](https://docs.docker.com/compose/networking/) in the Docker documentation. – David Maze Dec 28 '21 at 14:18
  • So, I tried getting the db to run as an image instead of on the localhost. I replaced the `DB_URI` to include `db` as the service name instead of `host.docker.internal`. Doing a `docker-compose up` seems to make it work despite some weird errors it throws at me. But running it on docker playground gives me a host not found error. I can edit them into the question but last time I tried that, all the comments disappeared. – Lazlo Dec 28 '21 at 17:00

1 Answers1

6

Add this to "app" service in docker compose

extra_hosts:
  - "host.docker.internal:host-gateway"

Then your app will be able to connect to mongodb running on host machine.