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
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 #################################################################');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With