0

I'm trying to use Docker as part of my testing suite. I have 2 containers set up as:

version: "3"
services:

  mongo_3_4:
    image: mongo:3.4
    command: ["mongod", "--smallfiles"]
    ports:
       - "27021:27017"

  frontend:
    build:
      context: ./Dockerfiles/path/
       dockerfile: Dockerfile
    ports:
      - "63175:63175"

The frontend has the ability to mount a mongoDb where I have to give it credentials of host and port, for example locally I would use localhost | 27021 and my db would be mounted.

The only way I can get it to currently work, is by getting the IP of the host machine. I achieved this by doing as described here : $ ipconfig getifaddr en0

thus getting the host machine IP and using it for mounting my db from the frontend ie 192.168.1.42 | 27021

The problem I have is this host IP will be different on various environments as it's used as part of a test suite. It would be used on various local machines with different OS's and say Travis-ci.

Is there a recommended way to hard code this host IP from within docker or would I have to create a script that works out the host and do this sudo ifconfig lo0 alias 192.168.46.49?

Just seem overly complicated when all I'm doing is having 2 containers and wanting one of them to be able to mount the db from the other?

Community
  • 1
  • 1
cmdv
  • 1,693
  • 3
  • 15
  • 23
  • This is basic [Docker Networking](https://docs.docker.com/engine/userguide/networking/). Take a look at [this answer](https://stackoverflow.com/a/34728404/174843) for a summary. – Vince Bowdren May 23 '17 at 14:06

1 Answers1

1

The host that runs docker is by default: 172.17.0.1. Have you tried that? (that is the localhost of your computer, roughly speaking)

Also, you can link containers and get benefits of docker networking:

version: "3"
services:

  mongo_3_4:
    image: mongo:3.4
    command: ["mongod", "--smallfiles"]
    ports:
       - "27021:27017"

  frontend:
    build:
      context: ./Dockerfiles/path/
      dockerfile: Dockerfile
    ports:
      - "63175:63175"
    links:
      - mongo_3_4:mongo

Then, you can access from frontend to mongo as this: mongo:27017

Robert
  • 33,429
  • 8
  • 90
  • 94
  • thank you this worked like a charm when using the `links` option. Still not able to use `localhost` but I'm more than happy with the ability to be able to `mongo:27017` one quick question though how come it doesn't use the port `27021`? – cmdv May 23 '17 at 15:59
  • mongo listen to 27017 on the internal container own IP address (maybe 172.17.0.X), so `mongo` resolve to that IP from the `frontend`, thanks to the `link`. The port 27021 is available to the **host** (your interfaces, i.e. your localhost), and it is not available in the internal container IP. Does it make sense? – Robert May 23 '17 at 16:23
  • So you can take `ports` out from the mongo_3_4 service. Frontend will still be able to access mongo – Robert May 23 '17 at 16:24