Create docker-compose file like the next:

model: '3.7'
companies:
  mongodb:
    picture: mongo:newest
    container_name: mongodb_contaner
    atmosphere:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: 12345678
      MONGO_INITDB_DATABASE: chat_app
    command:
      - '--logpath'
      - '/var/log/mongodb/mongod.log'
    ports:
      - 27017:27017
    volumes:
      - ./docker/mongodb_data:/knowledge/db
      - ./docker/init-mongo.js:/docker-entrypoint-initdb.d/init-mongo.js
Enter fullscreen mode

Exit fullscreen mode

Create a listing known as docker like the next:

mkdir -p docker/mongodb_data
Enter fullscreen mode

Exit fullscreen mode

*Create an init-mongo.js inside docker listing and with the next content material : *

db = db.getSiblingDB('admin');
db.auth('root', '12345678');

db = db.getSiblingDB('chat_app');
db.createUser({
  person: 'app_user',
  pwd: 'password',
  roles: [
    {
      role: 'readWrite',
      db: 'chat_app',
    },
  ],
});

db.createCollection('test_docker');
Enter fullscreen mode

Exit fullscreen mode

Run docker-compose to begin working the container:

docker-compose down && docker-compose construct --no-cache && docker-compose up -d
Enter fullscreen mode

Exit fullscreen mode

To examine every thing is working, SSH into the MongoDB container like the next:

//to SSH into the container
docker exec -it mongodb_contaner bash

mongod --version

//Test admin db connection is working or not
mongosh admin -u root -p

// examine default database with newly created by init-mongo.js
present dbs
Enter fullscreen mode

Exit fullscreen mode

source