Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

enter image description here

Please help me if something is missing

like image 722
Munish Kapoor Avatar asked Mar 04 '20 09:03

Munish Kapoor


Video Answer


1 Answers

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 #################################################################');
like image 138
Munish Kapoor Avatar answered Oct 28 '22 04:10

Munish Kapoor