5

I've moved my Mongodb from a container to a local service (it was really flaky when containerised). Problem is I cannot connect from a Node api into the locally running MongoDB service. I can get this working on my Mac, but not on Ubuntu. I've tried:

 - DB_HOST=mongodb://172.17.0.1:27017/proto?authSource=admin

 - DB_HOST=mongodb://localhost:27017/proto?authSource=admin

 // this works locally, but not on my Ubuntu server
 - DB_HOST=mongodb://host.docker.internal:27017/proto?authSource=admin

Tried adding this to my docker file:

  ip -4 route list match 0/0 | awk '{print $3 "host.docker.internal"}' >> /etc/hosts && \

Also tried network bridge to no avail. Example docker compose

version: '3.3'

services:
  search-api:
    build: ../search-api
    environment:
      - PORT=3333
      - DB_HOST=mongodb://host.docker.internal:27017/search?authSource=admin
      - DB_USER=dbuser
      - DB_PASS=password
    ports:
      - 3333:3333
    restart: always
Mark Robson
  • 1,298
  • 3
  • 15
  • 40
  • host.docker.internal only works on Mac only. Not on any Linux including Ubuntu. https://docs.docker.com/docker-for-mac/networking/#there-is-no-docker0-bridge-on-macos – techtabu Sep 20 '18 at 19:38
  • 2
    I got this working. Error was Mongodb was not set to listen on the correct ip address. Fixed that and could then connect. – Mark Robson Oct 29 '18 at 12:24

1 Answers1

2

Problem can be caused by MongoDb not listening on the correct ip address and therefore blocking your access.

Either make sure you're listening to a specific ip or listening to all: 0.0.0.0 On linux the config file is per default installed here: /etc/mongod.conf

Configuration specific Ip address:

net:
    bindIp: 172.17.0.1 #being your host's ip address
    port: 27017

Configuration open to all connections:

net:
    bindIp: 0.0.0.0
    port: 27017

To get your hosts ip address (from within a container) On docker-for-mac and docker-for-windows you can use host.docker.internal While on linux you need to run ip route show in the container.

When running Docker natively on Linux, you can access host services using the IP address of the docker0 interface. From inside the container, this will be your default route.

For example, on my system:

$ ip addr show docker0
7: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default 
    link/ether 00:00:00:00:00:00 brd ff:ff:ff:ff:ff:ff
    inet 172.17.0.1/16 brd 172.17.255.255 scope global docker0
       valid_lft forever preferred_lft forever
    inet6 fe80::f4d2:49ff:fedd:28a0/64 scope link 
       valid_lft forever preferred_lft forever

And inside a container:

# ip route show
default via 172.17.0.1 dev eth0 
172.17.0.0/16 dev eth0  src 172.17.0.4 

(copied from here: How to access host port from docker container)

Baklap4
  • 3,914
  • 2
  • 29
  • 56