My answer is based on the one provided by @x-yuri; but my scenario it's a little bit different. I wanted an image containing the script, not bind without needing to bind-mount it.
mongo-init.sh
-- don't know whether or not is need but but I ran chmod +x mongo-init.sh
also:
#!/bin/bash
# https://stackoverflow.com/a/53522699
# https://stackoverflow.com/a/37811764
mongo -- "$MONGO_INITDB_DATABASE" <<EOF
var rootUser = '$MONGO_INITDB_ROOT_USERNAME';
var rootPassword = '$MONGO_INITDB_ROOT_PASSWORD';
var user = '$MONGO_INITDB_USERNAME';
var passwd = '$MONGO_INITDB_PASSWORD';
var admin = db.getSiblingDB('admin');
admin.auth(rootUser, rootPassword);
db.createUser({
user: user,
pwd: passwd,
roles: [
{
role: "root",
db: "admin"
}
]
});
EOF
Dockerfile
:
FROM mongo:3.6
COPY mongo-init.sh /docker-entrypoint-initdb.d/mongo-init.sh
CMD [ "/docker-entrypoint-initdb.d/mongo-init.sh" ]
docker-compose.yml
:
version: '3'
services:
mongodb:
build: .
container_name: mongodb-test
environment:
- MONGO_INITDB_ROOT_USERNAME=root
- MONGO_INITDB_ROOT_PASSWORD=example
- MONGO_INITDB_USERNAME=myproject
- MONGO_INITDB_PASSWORD=myproject
- MONGO_INITDB_DATABASE=myproject
myproject:
image: myuser/myimage
restart: on-failure
container_name: myproject
environment:
- DB_URI=mongodb
- DB_HOST=mongodb-test
- DB_NAME=myproject
- DB_USERNAME=myproject
- DB_PASSWORD=myproject
- DB_OPTIONS=
- DB_PORT=27017
ports:
- "80:80"
After that, I went ahead and publish this Dockefile as an image to use in other projects.
note: without adding the CMD
it mongo throws: unbound variable error