How to read env variable in mongo-init.js? docker-compose.yml able to read from .env file but mongo-init.js can't as mongo-init.js will copy to /docker-entrypoint-initdb.d volume (not sure I'm right or wrong). This mean mongo-init.js will read process.env.MONGODB_USERNAME as undefined.
Is it possible to convert env value in mongo-init.js first before copy to /docker-entrypoint-initdb.d
docker-compose.yml
version: '2'
services:
mongodb:
image: mongo:4.4.2
restart: always
container_name: local-mongodb
environment:
MONGO_INITDB_ROOT_USERNAME: ${MONGODB_ROOT_USERNAME}
MONGO_INITDB_ROOT_PASSWORD: ${MONGODB_ROOT_PASSWORD}
ports:
- ${MONGODB_PORT}:27017
volumes:
- mongodb_database:/data/db
- ./mongo-init.js:/docker-entrypoint-initdb.d/mongo-init.js
volumes:
mongodb_data:
mongo-init.js
require('dotenv').config()
print('mongo init start --------------------');
const pms = db.getSiblingDB(process.env.MONGODB_DATABASE)
pms.createUser({
user: process.env.MONGODB_USERNAME,
pwd: process.env.MONGODB_PASSWORD,
roles: [
{
role: 'readWrite',
db: process.env.MONGODB_DATABASE,
},
],
});
print('mongo init end --------------------');
.env
MONGODB_ROOT_USERNAME=root
MONGODB_ROOT_PASSWORD=password
MONGODB_DATABASE=product
MONGODB_USERNAME=user
MONGODB_PASSWORD=password
MONGODB_PORT=27017