Quickly Spin Up MongoDB With Docker Compose

Quickly Spin Up MongoDB With Docker Compose

Learn How to Install MongoDB Using Docker Compose

In this tutorial, we'll learn how to install MongoDB using Docker-Compose. By using Docker-Compose, we can configure an image the way we want and can turn the image on and of as needed.

Setup

Create a new directory for your MongoDB project. Inside of this directory, create a data directory and a docker-compose.yml file.

Project_Folder_For_Database
|---data
|___docker-compose.yml

Inside for the docker-compose.yml file paste this:

version: '3.7'
services:
  mongodb_database:
    # Image name
    image: mongo
    environment:
      # set username and password  
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: rootpassword
    # set port  
    ports:
      - 27017:27017
    # set volume  
    volumes:
      - ./data:/data/db
    restart: always  

Start the Container

To start the container run this command:

 docker-compose up -d

Stop the Container

To stop the container run this command:

 docker-compose down
 

Persisting Data

Whenever MongoDB modifies any data it will be persist locally inside of your data directory.

Run Commands Inside of the Container

To run Bash commands run this command:

docker-compose exec mongodb_database bash

This will give you shell access to the container.

Conclusion

In this short tutorial, we'll learn how to spin up MongoDB with Docker-Compose and how to get shell access to the container.

Did you like it? Why don't you try also...

Docker MySQL, PostgreSQL, and MongoDB

Docker MySQL, PostgreSQL, and MongoDB

Learn how to use Docker to install MySQL, PostgreSQL, and MongoDB

Quickly Spin Up PostgreSQL With Docker Compose

Quickly Spin Up PostgreSQL With Docker Compose

Learn How to Install PostgreSQL Using Docker Compose

Quickly Spin Up MariaDB With Docker Compose

Quickly Spin Up MariaDB With Docker Compose

Learn How to Install MariaDB Using Docker Compose