mongod --bind_ip using docker-compose version 2

I could finally manage to get connected both containers. My findings here for documentation purposes.

Main points

  • docker-compose version 2 creates a bridge network and adds all the containers to it.
  • mongod is not aware of this network and therefore doesn't bind to that ip. By default, binds only to 127.0.0.1
  • mongoimport could not establish connection using container name, even though it's supposed to be translated to the container ip.

Solution

  • Assign an static IP for the mongodb through the explicit definition of a network
  • Init mongo container with --bind_ip flag pointing to that static ip
  • Use ip address instead of hostname with mongoimport

docker-compose.yml

version: '2'

services:
  mongodb:
    image: mongo:3.2
    ports:
      - "27017:27017"
    networks:
      mongo_net:
        ipv4_address: 172.16.0.1
    command: mongod --bind_ip 127.0.0.1,172.16.0.1

  mongo-seed:
    build: ./mongo-seed
    networks:
      mongo_net:
    depends_on:
      - mongodb

networks:
  mongo_net:
    driver: bridge
    ipam:
      config:
      - subnet: 172.16.0.0/24
        gateway: 172.16.0.254

mongo-seed/Dockerfile

FROM mongo:3.2

COPY init.json /init.json
CMD mongoimport --host 172.16.0.1 --db test --collection users \
   --type json --file /init.json --jsonArray