Home > Back-end >  Can't see my mongo database when using mongo cmd on a Docker container
Can't see my mongo database when using mongo cmd on a Docker container

Time:12-18

Similar to Can't connect to MongoDB container from other Docker container - but answers from this post don't work for me.

I am new to Docker. Trying to learn it on a typescript/express/mongo/mongoose api example.

What I am trying to do (and having problems with), is to use mongo cmd line on a running mongo container after it has been spun up using docker compose up. Even though I have my data nicely persisted on a Docker volume, I don't seem to be able to log into the database using cmd line.

This is my docker-compose.yml file:

version: '3.9'
services:
  api:
    container_name: api_ts
    build: .
    restart: unless-stopped
    environment:
      - DB_URL=mongodb://myself:pass123@mongo:27017/
    ports:
      - '3131:3131'
    depends_on:
      - mongo
    links: # (seems to be needed)
      - mongo
  mongo:
    container_name: mongo_container
    image: mongo:latest
    restart: always
    volumes:
      - mongo_dbv:/data/db
    environment:
      - MONGO_INITDB_ROOT_USERNAME=myself
      - MONGO_INITDB_ROOT_PASSWORD=pass123
    ports:
      - '27017:27017'
volumes:
  mongo_dbv: {}

This is my Dockerfile:

FROM node:alpine
WORKDIR /usr/src/app
COPY package*.json .
RUN npm ci
COPY . .
ENV PORT=3131
EXPOSE 3131
COPY .env ./dist
CMD ["npm", "start"]

I am running

docker compose up -d --build

After both services are ready, I do:

docker exec -it mongo_container mongo
show dbs

...and the output of the last cmd is empty

(same occurs when trying to follow the answers in the post mentioned above)

I am sure the database contains data, because I am able to verify it using REST client.

Also, I am a bit puzzled - and maybe this is somehow connected - why there is no indication, either in docker-compose.yml or in Dockerfile, of the database name which I am using. I would expect it to be part of show dbs output. Despite that, my api runs just fine.

CodePudding user response:

Listing databases requires authentication

docker exec -it mongo_container mongo -u myself -p pass123

Now you can list databases

> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB

Note: mongo should show you warning that "mongo" shell has been superseded by "mongosh". When you use mongosh, a proper authentication error would be shown on the database listing attempt.

  • Related