'Docker Compose MongoDB docker-entrypoint-initdb.d is not working
I am using following docker-compose file
version: '3.7'
services:
 db_container:
  image: mongo:latest
  restart: always
  environment:
    MONGO_INITDB_ROOT_USERNAME: root
    MONGO_INITDB_ROOT_PASSWORD: password
    MONGO_INITDB_DATABASE: root-db
  ports:
    - 27017:27017
  volumes:
    - ./database/initdb.js:/docker-entrypoint-initdb.d/initdb.js:ro
    - ./data:/data/db
Here is my initdb.js file
db.createUser(
{
  user: "api-test",
  pwd: "api-test",
  roles: [
    {
      role: "readWrite",
      db: "api-test"
    }
  ]
}
);
I can see only 3 databases  and unable to connect to api-test DB
Please help me if something is missing
Solution 1:[1]
Able to solve the issue with the help of the following article Docker-Compose mongoDB Prod, Dev, Test Environment
The file structure should be
Project
??? docker-compose.yml (File)
??? docker-entrypoint-initdb.d (Directory)
?   ??? mongo-init.js (File)
docker-compose.yml file
version: '3.7'
services:
   mongo:
    container_name: container-mongodb
    image: mongo:latest
    restart: always
    ports:
      - 27017:27017
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: password
      MONGO_INITDB_DATABASE: root-db
    volumes:
      - ./docker-entrypoint-initdb.d/mongo-init.js:/docker-entrypoint-initdb.d/mongo-init.js:ro
mongo-init.js file
print('Start #################################################################');
db = db.getSiblingDB('api_prod_db');
db.createUser(
  {
    user: 'api_user',
    pwd: 'api1234',
    roles: [{ role: 'readWrite', db: 'api_prod_db' }],
  },
);
db.createCollection('users');
db = db.getSiblingDB('api_dev_db');
db.createUser(
  {
    user: 'api_user',
    pwd: 'api1234',
    roles: [{ role: 'readWrite', db: 'api_dev_db' }],
  },
);
db.createCollection('users');
db = db.getSiblingDB('api_test_db');
db.createUser(
  {
    user: 'api_user',
    pwd: 'api1234',
    roles: [{ role: 'readWrite', db: 'api_test_db' }],
  },
);
db.createCollection('users');
print('END #################################################################');
Solution 2:[2]
Although my setup was correct, removed volumes, modified the db, etc, none of these worked for me.
The only way was to change the name of the mongodb container inside the docker-compose, instead of mongo I wrote mongodb and it worked.
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 | Munish Kapoor | 
| Solution 2 | decoder | 

