To set up and run MongoDB using Docker Compose, follow these steps:

 

Install Docker and Docker Compose

Make sure you have Docker and Docker Compose installed on your system.

Refer to Installing Docker on Ubuntu 22: Streamlining Containerization Without Sudo

Create a Docker Compose YAML file

Create a new file called docker-compose.yml and open it in a text editor. Add the following content to the file:

version: '3.8'
services:
mongodb:
image: mongo
ports:
- 27017:27017
volumes:
- mongodb_data:/data/db
volumes:
mongodb_data:

In the above configuration, we define a service named mongodb using the official MongoDB Docker image. We expose port 27017 to allow connections to the MongoDB server. We also specify a named volume mongodb_data to persist the MongoDB data on the host system.

Start MongoDB using Docker Compose

Open a terminal, navigate to the directory where your `docker-compose.yml` file is located, and run the following command to start MongoDB:

docker-compose up -d

This command starts the MongoDB service in detached mode (`-d` flag) so that it runs in the background. Docker Compose will automatically pull the MongoDB image if it is not already available and start the container.

 

Verify MongoDB Container

To verify that the MongoDB container is running, you can use the following command:

docker-compose ps

You should see the mongodb service listed as "Up".

 

Connect to MongoDB

You can now connect to MongoDB using a MongoDB client or your application. The MongoDB server is accessible at localhost:27017. You can use the MongoDB URI mongodb://localhost:27017 to connect.

 

Stop and Remove MongoDB Container

To stop and remove the MongoDB container when you no longer need it, use the following command:

docker-compose down

This command stops and removes the containers defined in the `docker-compose.yml` file.

 

That's it! You have set up and run MongoDB using Docker Compose. Docker Compose simplifies the process of managing the MongoDB container and allows you to easily reproduce the environment on different systems.

More Articles on this topic: