You can base your solution on the example below if you wish to run some MongoDB migration scripts at the Docker startup. It could be anything like adding users, database, collection so on. You can find example export and import comments at the bottom.


Docker compose


Last four environment variables are our custom ones that we would use within our application.


# docker/docker-compose.yaml

version: "3.4"

services:

mongodb:
image: "mongo:4.0"
ports:
- "27017:27017"
environment:
MONGO_INITDB_ROOT_USERNAME: "root"
MONGO_INITDB_ROOT_PASSWORD: "root"
MONGO_NAME: "blog"
MONGO_USER: "inanzzz"
MONGO_PASS: "1234567"
MONGO_AUTH: "SCRAM-SHA-256"
volumes:
- "./mongodb:/docker-entrypoint-initdb.d"

Collection dump


# docker/mongodb/comments.json

[
{
"_id": {
"$oid": "604b8b6d4121340ffc6fe038"
},
"uuid": "805e6630-da37-4544-8005-d0568932b1dd",
"text": "Hello - 273324000",
"created_at": {
"$date": "2021-03-12T15:40:29.273Z"
}
},
{
"_id": {
"$oid": "604b8b6f4121340ffc6fe039"
},
"uuid": "21ddc064-7b93-42a9-a1a5-af1208256677",
"text": "Hello - 469124000",
"created_at": {
"$date": "2021-03-12T15:40:31.469Z"
}
},
{
"_id": {
"$oid": "604b8b714121340ffc6fe03a"
},
"uuid": "39b5c13e-07fe-4ea6-bd2f-31db7ff2eaf8",
"text": "Hello - 489378000",
"created_at": {
"$date": "2021-03-12T15:40:33.489Z"
}
}
]

Query script


You can extend it as you wish.


# docker/mongodb/init.sh

#!/bin/sh

# Create a custom user with a password, role and auth mechanism. This user will
# be used by the application for MongoDB connection.
mongo \
-u ${MONGO_INITDB_ROOT_USERNAME} \
-p ${MONGO_INITDB_ROOT_PASSWORD} \
--authenticationDatabase admin ${MONGO_NAME} \
<<-EOJS
db.createUser({
user: "${MONGO_USER}",
pwd: "${MONGO_PASS}",
roles: [{
role: "readWrite",
db: "${MONGO_NAME}"
}],
mechanisms: ["${MONGO_AUTH}"],
})
EOJS

# Prepare database.
mongo \
-u ${MONGO_INITDB_ROOT_USERNAME} \
-p ${MONGO_INITDB_ROOT_PASSWORD} \
--authenticationDatabase admin ${MONGO_NAME} \
<<-EOJS
use ${MONGO_NAME}
db.createCollection("comments")
db.comments.createIndex({"uuid":1},{unique:true,name:"UQ_uuid"})
EOJS

# Migrate dump.
mongoimport \
--db ${MONGO_NAME} \
--collection comments \
--username ${MONGO_INITDB_ROOT_USERNAME} \
--password ${MONGO_INITDB_ROOT_PASSWORD} \
--authenticationDatabase admin \
--jsonArray \
--file /docker-entrypoint-initdb.d/comments.json

Test


I assume that your container is running!


$ docker exec -it mongodb bash

/# mongo -u root -p root --authenticationDatabase admin blog
MongoDB shell version v4.0.21
connecting to: mongodb://127.0.0.1:27017/blog?authSource=admin&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("bd9fe616-45f5-4ab9-a10f-d2d66e9f046b") }
MongoDB server version: 4.0.21
Welcome to the MongoDB shell.

> show users
{
"_id" : "blog.inanzzz",
"userId" : UUID("f5632701-4184-477a-9275-d767f705c2d6"),
"user" : "inanzzz",
"db" : "blog",
"roles" : [
{
"role" : "readWrite",
"db" : "blog"
}
],
"mechanisms" : [
"SCRAM-SHA-256"
]
}

> show dbs
admin 0.000GB
blog 0.001GB
config 0.000GB
local 0.000GB

> show collections
comments

> db.comments.find({})
{ "_id" : ObjectId("604b8b6d4121340ffc6fe038"), "uuid" : "805e6630-da37-4544-8005-d0568932b1dd", "text" : "Hello - 273324000", "created_at" : ISODate("2021-03-12T15:40:29.273Z") }
{ "_id" : ObjectId("604b8b714121340ffc6fe03a"), "uuid" : "39b5c13e-07fe-4ea6-bd2f-31db7ff2eaf8", "text" : "Hello - 489378000", "created_at" : ISODate("2021-03-12T15:40:33.489Z") }
{ "_id" : ObjectId("604b8b6f4121340ffc6fe039"), "uuid" : "21ddc064-7b93-42a9-a1a5-af1208256677", "text" : "Hello - 469124000", "created_at" : ISODate("2021-03-12T15:40:31.469Z") }

For the connection within the application, you will use properties below. This is for Golang but you get the picture! Also, when using a OS client to connect to MongoDB, you will need to use same credentials.


# Configuration.
Config{
Auth: "SCRAM-SHA-256",
Host: "localhost",
Port: "27017",
User: "inanzzz",
Pass: "1234567",
Name: "blog",
}

# Client connection.
mongo.Connect(ctx, options.Client().
SetAuth(options.Credential{
AuthMechanism: config.Auth,
AuthSource: config.Name,
Username: config.User,
Password: config.Pass,
}).
ApplyURI(fmt.Sprintf("mongodb://%s:%s", config.Host, config.Port)),
)

# Database selection.
mon.Database(config.Name)

Export/Import collection


All below would work.


mongoexport \
--db blog \
--collection comments \
--username root \
--password root \
--authenticationDatabase admin \
--jsonArray \
--pretty \
--out blog-comments.json

mongoexport \
--db blog \
--collection comments \
--username inanzzz \
--password 1234567 \
--authenticationDatabase admin \
--jsonArray \
--pretty \
--out blog-comments.json

mongoimport \
--db blog \
--collection comments \
--username root \
--password root \
--authenticationDatabase admin \
--jsonArray \
--file blog-comments.json

mongoimport \
--db blog \
--collection comments \
--username inanzzz \
--password 1234567 \
--authenticationDatabase blog \
--jsonArray \
--file blog-comments.json