How To Create a DB For MongoDB Container on Start Up?

In this post, we will get to know How to create a DB for a MongoDB container on a startup which we can do by using the MongoinitDB database environment variable in the docker run command. and we can also use a custom endpoint script but we need to run before any MongoDB server start. and we will see the steps to implement the same.


Create A Database On Start Up

This we can perform in two different ways like on docker and by entry point and here we will discuss both of the ways and implement the same as per our requirements.

By Docker

As we can use so in Dockerby simply a command which is given below, followed by the explanation of the same.

docker run --name my-mongo -e MONGO_INITDB_DATABASE=my-db -d mongo

The command given above is going to make a new container called “my-mongo”, sets the mongo to init db database environment variable to “my- db”, and runs the official MongoDB image in detached mode -d.

When the container starts up, the mongo image will automatically make a database called “my- db” and start the MongoDB server. You can connect to the database using any MongoDB client and start inserting data.


As we can use a custom entrypoint script which we need to run before the start of the server and to implement it we have given an example of code below to get it done. by simply following the steps given below.

  1. Create a custom script:

if [ ! -z "$MONGO_INITDB_DATABASE" ]; then
    mongo <<EOF
            user: "$MONGO_INITDB_ROOT_USERNAME",
            pwd: "$MONGO_INITDB_ROOT_PASSWORD",
            roles: [ { role: "readWrite", db: "$MONGO_INITDB_DATABASE" } ]

exec mongod "$@"
2. Build a custom Docker image

Simply run the command given below.

docker build -t my-mongo .
3. Rin The container

To get it done simply follow the command given below.

docker run --name my-mongo -e MONGO_INITDB_DATABASE= my-db -e MONGO_INITDB_ROOT_USERNAME= my-user -e MONGO_INITDB_ROOT_PASSWORD= my-password -d my-mongo

This command makes a new container called “my-mongo”, sets the mongo initdb database, MongoDB initdb root username, and MongoDB initdb root password environment variables, and runs your custom my mongo image in detached mode.


To learn more about How to create a DB for a MongoDB container on start up visit: by Stack overflow.

To learn more about MongoDB and tutorial related to it visit: MongoDB Problems And Tutorials

Leave a Comment

%d bloggers like this: