MongoDB on with Docker "failed to connect to server [localhost:27017] on first connect "

By default Compose sets up a single network for your app. Each container for a service joins the default network and is both reachable by other containers on that network, and discoverable by them at a hostname identical to the container name.

According to your docker-compose.yaml file you can access you mongo container on 127.0.0.1:27017 only from host machine. In order to access it from NodeJS backend container you should use db:27017.


I have the same problem, other solutions not work for me but I did that this way

Note :

for mongo URI you must use your MongoDB service name instead 127.0.0.1 or localhost

for example, in below docker-compose file my mongo service name is mongodb-myapp and I change URI like this mongodb://mongodb-myapp:27017/myapp and it works for me


services:
  boilerplate-api-app:
    build: .
    environment:
      - MONGO_URI=mongodb://mongodb-myapp:27017/myapp
    volumes:
      - .:/app
    ports:
      - "5000:5000"
    depends_on:
      - mongodb-myapp

 mongodb-myapp:
    image: mongo
    ports:
      - "27017:27017"