Deploy MongoDB Container with Docker Compose

Introduction

MongoDB is a popular, open-source NoSQL database management system that falls under the category of document-oriented databases. Developed by MongoDB Inc., it provides a flexible and scalable solution for storing and retrieving data in a way that is different from traditional relational database management systems (RDBMS).

Docker Compose is a tool for defining and running multi-container Docker applications. It allows you to define an entire application stack, including services, networks, and volumes, in a single file called docker-compose.yml. With a single command, you can then spin up your entire application stack, simplifying the process of managing and deploying multi-container Docker applications.

Prerequisites

  • Up and running ubuntu 22.04 LTS machine.
  • Basic knowledge in linux commands.
  • Internet connectivity.
  • Docker and docker compose should installed on your machine.

To install Docker and docker compose on ubuntu 22.04 LTS, We can use the given link.

In this post, We will deploy MongoDB container using Docker Compose on Ubuntu 22.04 LTS machine.

Step 1: Creating docker-compose.yml

To deploy a MongoDB container using Docker Compose, you’ll need to create a docker-compose.yml file that defines the service. Here’s a simple example:

To create a docker-compose.yml

sudo nano docker-compose.yml

Copy and paste the followings configuration.

version: '3'

services:
  mongodb:
    image: mongo
    container_name: my_mongodb
    ports:
      - "27017:27017"
    volumes:
      - mongodb_data:/data/db
    environment:
      MONGO_INITDB_ROOT_USERNAME: your_username
      MONGO_INITDB_ROOT_PASSWORD: your_password

volumes:
  mongodb_data:

Save and exit from the nano text editor and in this above example we are using following config.

  • image: mongo: Specifies the official MongoDB Docker image.
  • container_name: my_mongodb: Assigns a name to the MongoDB container.
  • ports: – “27017:27017”: Maps the container’s port 27017 to the host machine’s port 27017, allowing you to access MongoDB from your host machine.
  • volumes: – mongodb_data:/data/db: Creates a Docker volume named mongodb_data and mounts it to the /data/db directory in the MongoDB container. This is where MongoDB stores its data.
  • environment:: Sets environment variables for configuring MongoDB. In this example, it sets the root username and password for MongoDB.

Step 2: Deploy MongoDB Container

To deploy this MongoDB service, follow these steps, Run the following command to start the MangoDB container:

sudo docker-compose up -d

The -d flag runs the containers in the background, It will take few sec or mins to pull the image and deploy the MongoDB.

Step 3: Validate the Container

To check the running containers launched by Docker Compose, you can use the following command:

sudo docker-compose ps

This command provides a summary of the status of each service defined in your docker-compose.yml file. It shows information such as the service name, container ID, status, ports, and names.

Here’s an example of what the output might look like:

   Name                 Command            State               Ports
-------------------------------------------------------------------------
mongodb   docker-entrypoint.sh mongodb   Up      0.0.0.0:3306->27017/tcp

Step 4: Logging

Some time we need to also check the real time logs, So we can use the given commands.

sudo docker-compose logs -f mongodb

Step 5: MongoDB connection PHP

To connect to MongoDB using PHP, you can use the official MongoDB PHP extension, which provides a driver for interacting with MongoDB. Below is an example PHP script that demonstrates how to connect to a MongoDB database and perform some basic operations. Before running this script, make sure you have the MongoDB PHP extension installed. You can install it using Composer.

Install the MongoDB PHP extension using Composer:

composer require mongodb/mongodb

Create a PHP script (e.g., mongo_example.php) with the following content:

<?php

require 'vendor/autoload.php'; // Autoload the MongoDB PHP extension

use MongoDB\Client;

// Replace the following with your MongoDB connection string
$mongoConnectionString = 'mongodb://your_username:your_password@localhost:27017/your_database';

// Create a MongoDB client
$client = new Client($mongoConnectionString);

// Select a database
$database = $client->your_database;

// Select a collection
$collection = $database->your_collection;

// Insert a document
$insertResult = $collection->insertOne([
    'name' => 'John Doe',
    'age' => 30,
    'city' => 'New York',
]);

echo "Inserted document with ID: " . $insertResult->getInsertedId() . "\n";

// Find a document
$document = $collection->findOne(['name' => 'John Doe']);

echo "Found document:\n";
var_dump($document);

// Update a document
$updateResult = $collection->updateOne(
    ['name' => 'John Doe'],
    ['$set' => ['age' => 31]]
);

echo "Matched " . $updateResult->getMatchedCount() . " document(s) and modified " . $updateResult->getModifiedCount() . " document(s)\n";

// Delete a document
$deleteResult = $collection->deleteOne(['name' => 'John Doe']);

echo "Deleted " . $deleteResult->getDeletedCount() . " document(s)\n";

Replace the placeholders (your_username, your_password, localhost:27017, your_database, and your_collection) in the connection string with your MongoDB credentials and connection details.

Run the PHP script:

php mongo_example.php

Step 6: Destroy MongoDB Container

To destroy (stop and remove) the MangoDB container launched with Docker Compose, you can use the following command in the directory where your docker-compose.yml file is located:

sudo docker-compose down

This command stops and removes all the containers, networks, and volumes defined in your docker-compose.yml file.

The down command stops and removes the containers but retains the data volumes by default. If you want to remove the volumes as well, you can use the -v option:

sudo docker-compose down -v

Make sure you are in the correct directory containing your docker-compose.yml file when running these commands. This ensures that Docker Compose identifies the correct configuration file.

After running the docker-compose down command, you can use the docker-compose ps command to verify that the containers are no longer running. The output should be empty, indicating that no containers are currently running.

Remember that this command will stop and remove all the services defined in your docker-compose.yml file, not just the MangoDB service. If you only want to remove a specific service, you can specify the service name:

docker-compose down -v <service_name>

Replace <service_name> with the actual name of the service you want to remove.

Conclusion

We have successfully deployed MongoDB database server on docker’s container using docker compose on ubuntu 22.04 LTS machine, If you still have questions, please post them in the comments section below.

Author

Deploy MongoDB Container with Docker Compose

One thought on “Deploy MongoDB Container with Docker Compose

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top