1

I've built two NEST app which shares a common database. I've been trying to figure out a way to make these two apps to get data from the Mongo db container. I'm stuck with this process.

docker-compose.yml with app 1

version: '3'

services:  
  backend:
    image: 'example-image_1:1.0.0'
    working_dir: /app/example-app-1/backend/example-app-1-api
    environment:
      - DB_URL=mongodb://0.0.0.0:27017/example_app_1
      - BACKEND_PORT=3333
      - BACKEND_IP=0.0.0.0
    restart: always
    network_mode: "host"
    ports:
      - '3333:3333'
    command: ['node', 'main.js']
    depends_on:
      - mongodb

    expose:
      - 3333

  mongodb:
    image: 'mongo:latest'
    environment:
      - 'MONGODB_DATABASE="example_app_1"'
    ports:
      - '27017:27017'
    expose:
      - 27017

docker-compose.yml with app-2

version: '3'

services:   
  backend:
    image: 'example_app_2:1.0.0'
    working_dir: /app/example_app_2/backend/example-app-2-api
    environment:
      - DB_URL=mongodb://0.0.0.0:27017/example_app_2
      - BACKEND_PORT=8888
      - BACKEND_IP=0.0.0.0
    restart: always
    ports:
      - '8888:8888'
    command: ['node', 'main.js']
    expose:
      - 8888

  mongodb:
    image: 'mongo:latest'
    environment:
      - 'MONGODB_DATABASE="example_app_2"'
    ports:
      - '27017:27017'
    expose:
      - 27017

I need help in making these app communicate with common container - mongodb

Click link for Architecture Setup

1 Answer 1

1

Since you're using 2 different docker-compose.yml you're actually running 2 backend and 2 mongodb on 2 docker-networks

One of the 2 mongo won't start cause the port is already occupied.

Option 1 (nicer):

services:   
  backend_1:
      ...
    ports:
      - '8888:8888'
  backend_2:
      ...
    ports:
      - '8899:8899'

  mongodb:
    ports:
      - '27017:27017'

This setup provides 3 container on the same network. Now you can access at mongo from both backends at <mongo_ip>:27017

Option 2 (ugly):

services:   
  backend:
      ...
    ports:
      - '8888:8888'

  mongodb:
    ports:
      - '27017:27017'

And in another docker-compose

services:   
  backend:
      ...
    ports:
      - '8888:8888'

This setup provides 3 container on 2 different network. In this setup each docker-compose.yml has it's own docker network, so from the second backend service you have to connect to another docker network to access the container.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.