'Can't connect to mongoDB in docker container

I'm currently working on an api. When I run my api on my local computer I can connect to MongoDB but when I run it from the docker container, I cannot connect to MongoDB

I tried this to connect to the container : mongodb://0.0.0.0:27018 and mongodb://127.0.0.1:27018

I also check if the two containers can communicate together and they can so I don't know how to do it

There is my docker-compose

version: "3.9"
services:
  api:
    build:
      context: .
      dockerfile: Dockerfile
    ports:
      - "3001:3001"
    volumes:
      - .:/app
  mongo:
    container_name: "sell-mongodb"
    image: mongo
    ports:
      - "27018:27017"
    volumes:
      - mongodb-data:/data/db/
volumes:
  mongodb-data:


Solution 1:[1]

Use mongodb://mongo:27017.

Use mongo as hostname, because it is the name of your MongoDB service in Docker Compose. By default, Docker enables you to access other containers by this service hostnames.

Do not use 27018 port when connecting from within another container, as it is a port exposed to your host machine. Port 27017 on the other hand should be accessible by default from the internal docker network, i.e. from other containers. See https://docs.docker.com/compose/compose-file/compose-file-v3/#ports

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user14967413