Home > OS >  Can't connect to MongoDB inside docker container
Can't connect to MongoDB inside docker container

Time:12-07

I'm trying to connect to a mongodb container inside docker but I'm getting this error:

getaddrinfo ENOTFOUND mongo.ks.local

The database works just fine when I access it from docker but I'm not able to access it from MongoDBCompass

This is my docker-compose.yml file:

version: '3.8'

services:
  mongo:
    image: mongo
    container_name: mongo.ks.local
    restart: always
    environment:
      MONGO_INITDB_ROOT_USERNAME: <username>
      MONGO_INITDB_ROOT_PASSWORD: <password>
    ports:
      - 27017:27017
    volumes:
      - ks_mongodb:/data/db

I'm quite new to docker and will appreciate any help I can get

CodePudding user response:

You need the ip address of the container:

try:

 docker inspect <CONTAINER NAME>

And search for the ip address. Then use the ip address to connect to mongodb

CodePudding user response:

I have tried connecting to the container using mongo compass. It failed but when I removed the line of mounting the volume and tried again it connects to the database. Then tried to mount the volume like below it worked. I have changed the username and password and specified the INITDB env variable.

version: "3.8"
services:
  mongo:
    image: mongo:latest
    container_name: mongo.ks.local
    restart: always
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: 1234
      MONGO_INITDB_DATABASE: admin

    ports:
      - 27017:27017
    volumes:
      - /data/db
  • Related