skip to Main Content

I have two containers, one container is my next.js app and the other one is mongodb.

I create them by using docker compose up

Although they’re on the same network it looks like they can’t see each other. ( I verified this due to docs and also docker network inspect command)

my compose.yml looks like this:

services:
  web:
    build: .
    ports:
      - "3000:3000" 
  db:
    image: mongo:4.4.6
    expose: 
      - "27017" 

If I publish both of them it works just fine ( I refer the database URL as mongodb://db:27017/database in my .env.local)

But as a best practice I should only publish the app and expose the db to the app.

the working compose.yml file is:

services:
  web:
    build: .
    ports:
      - "3000:3000" 
  db:
    image: mongo:4.4.6
    ports: 
      - "27017:27017" 

2

Answers


  1. try using

    mongodb://localhost:27017/database
    

    or

    mongodb://127.0.0.1:27017/database
    
    Login or Signup to reply.
  2. You might be missing the "depends_on" section in your app specification. By adding it, you indicate that your app depends on your db service and will start only once the service is ready. It should look like this:

    services:
      web:
        build: .
        ports:
          - "3000:3000" 
        depends_on:
          - db
      db:
        image: mongo:4.4.6
        ports: 
          - "27017:27017" 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search