1

I am working on preparing docker compose file for some needs and I need to access locally running mongo-db within docker container. In this case, I am using Ubuntu 18.04 as host machine. But other people would also use OS X and Windows but this is not the priority right now.

So, for that, I can use network_mode: "host" in docker-compose.yml but with that, I can not use port-forwarding. (Just fyi, I tried that and it is working well) So I was looking for another solutions and with docker v2.10.0+, other people (ie.) suggested to use "host.docker.internal:host-gateway". I tried that and when I am using it, I am getting following error when I would like to access some data from locally, I am getting following error.

pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused, Timeout: 30s, Topology Description: <TopologyDescription id: 614c4d4212a8375b66727410, topology_type: Single, servers: [<ServerDescription ('localhost', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('localhost:27017: [Errno 111] Connection refused')>]>

This was not the case when I use network_mode: "host" though. So I am looking forward to way to use my locally running mongo-db within docker-container and port-forwarding should be accessible as well.

My current docker-compose file as following

version: '3.9'
services:

  engine:
    build: .
    entrypoint: 
      - /bin/bash
    extra_hosts:
      - "host.docker.internal:host-gateway"

That question is different than that as we have special condition with MongoDB and would like to solve problem without blocking port-forwarding so we can not use network_mode = "host"

herdogan
  • 101
  • 6
  • just to make sure: Is the MongoDB service running on your machine? [Someone else got a similar error message as well](https://stackoverflow.com/questions/69281311/python-pymongo-keeps-refusing-errno111-connection-refused-timeout-30s) – Ferhat Sep 23 '21 at 10:26
  • 1
    I don't think there's a 100% reliable cross-platform setup for this. `network_mode: host` only works on native Linux (and isn't usually a best practice); but on MacOS and Windows, Docker itself provides the `host.docker.internal` name and you don't need the `extra_hosts:` block. The linked question goes into a lot of detail on this. The important detail you might be missing is that you need to configure the database location as `host.docker.internal` (with or without the `extra_hosts:`), not as `localhost` ("this container"). – David Maze Sep 23 '21 at 10:57
  • have you tried setting `host.docker.internal` instead of `localhost` when connecting from the container to the MongoDB instance as suggested in the previous comment? – Noam Yizraeli Oct 18 '21 at 15:53

0 Answers0