Search code examples
mongodbdockerdocker-compose

How to create a DB for MongoDB container on start up?


I am working with Docker and I have a stack with PHP, MySQL, Apache and Redis. I need to add MongoDB now so I was checking the Dockerfile for the latest version and also the docker-entrypoint.sh file from the MongoDB Dockerhub but I couldn't find a way to setup a default DB, admin user/password and possibly auth method for the container from a docker-compose.yml file.

In MySQL you can setup some ENV variables as for example:

db:
    image: mysql:5.7
    env_file: .env
    environment:
      MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}
      MYSQL_DATABASE: ${MYSQL_DATABASE}
      MYSQL_USER: ${MYSQL_USER}
      MYSQL_PASSWORD: ${MYSQL_PASSWORD}

And this will setup the DB and the user/password as the root password.

Is there any way to achieve the same with MongoDB? Anyone has some experience or workaround?


Solution

  • Here another cleaner solution by using docker-compose and a js script.

    This example assumes that both files (docker-compose.yml and mongo-init.js) lay in the same folder.

    docker-compose.yml

    version: '3.7'
    
    services:
        mongodb:
            image: mongo:latest
            container_name: mongodb
            restart: always
            environment:
                MONGO_INITDB_ROOT_USERNAME: <admin-user>
                MONGO_INITDB_ROOT_PASSWORD: <admin-password>
                MONGO_INITDB_DATABASE: <database to create>
            ports:
                - 27017:27017
            volumes:
                - ./mongo-init.js:/docker-entrypoint-initdb.d/mongo-init.js:ro
    

    mongo-init.js

    db.createUser(
            {
                user: "<user for database which shall be created>",
                pwd: "<password of user>",
                roles: [
                    {
                        role: "readWrite",
                        db: "<database to create>"
                    }
                ]
            }
    );
    

    Then simply start the service by running the following docker-compose command

    docker-compose up --build -d mongodb 
    

    Note: The code in the docker-entrypoint-init.d folder is only executed if the database has never been initialized before.