Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading