'Unable to name a Mongo database in Docker compose

Can anyone tell me where I am going wrong. All I am trying to do is name a Mongo database using docker compose.

I have a docker compose file that looks like this:

version: "3"
services:
  mongo-db:
    image: mongo
    environment:
      - MONGO_INITDB_ROOT_USERNAME=admin
      - MONGO_INITDB_ROOT_PASSWORD=password
      - MONGO_INITDB_DATABASE=mydbname
    ports:
      - 27017:27017
    volumes:
      - mongo-db:/data/db

volumes:
  mongo-db:

I run docker docker-compose -f docker-compose.yml up -d --build and it runs. I then open Robo 3T and connect to my container but every time I do the database is called test and not mydbname. Any ideas? TIA



Solution 1:[1]

The environment variables are only used to create a new database if no database already exists. You map a volume to /data/db and that volume probably contains an existing database named 'test'.

Find the volume using docker volume ls. It's called something like <directory name>_mongo-db. Then delete it using docker volume rm <volume name>.

Now Docker will create a new, empty volume and Mongo will create a new database when you start the container. And it'll use the values from the environment variables.

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