MongoDB as a Docker Container

Learn via video courses
Topics Covered

Overview

MongoDB is a popular NoSQL document-oriented database with high scalability, performance, and flexibility for managing unstructured data. Docker is a containerization platform that allows you to run applications and services in isolated environments called containers.

Leveraging MongoDB Docker allows you to benefit from the flexibility of a popular NoSQL document-oriented database and the power of a containerization platform. Running a MongoDB docker container offers numerous advantages, such as easy deployment, portability, and scalability. Bundling the database and dependencies into a single container ensures consistent deployment across environments, and you can horizontally scale by creating multiple container instances to improve performance and resilience in high-traffic scenarios.

What is Docker?

Docker is a popular platform that enables developers to create, deploy, and run applications in isolated containers. Containers are standalone, lightweight, and executable packages that include all the necessary software, libraries, and dependencies required to run the application. Docker simplifies application deployment by packaging applications and their dependencies into portable containers that can run in isolated environments. This enables consistent and flexible deployment across various environments. Docker has become popular for its ability to streamline software delivery, improve application portability, and increase deployment flexibility in many industries.

Docker Components

Docker is composed of several components that work together to provide a containerization platform including:

Docker Engine: This is the core component of Docker that provides the runtime environment for containers. It includes the Docker daemon, API, and CLI tools that enable developers to create, manage, and run containers.

Docker Images: An image is a lightweight, standalone executable package that includes all the dependencies and configurations required to run an application in a container. Docker images can be shared and reused across different environments.

Docker Registry: A registry is a centralized repository that stores Docker images. Docker Hub is the default registry provided by Docker, but developers can also create their private registry to host and distribute their images.

Docker Compose: Docker Compose is a tool that enables developers to define and manage multi-container applications using a YAML file. It simplifies the process of deploying and scaling complex applications by defining the relationships between containers and their dependencies.

Docker Swarm: Docker Swarm is a native clustering and orchestration tool that enables developers to manage a cluster of Docker nodes and deploy containers across multiple hosts. It provides features such as load balancing, service discovery, and high availability.

Docker CLI: Docker provides a command-line interface (CLI) that enables developers to interact with the Docker Engine and perform various operations, such as creating and managing containers, images, networks, and volumes.

Docker Container

A Docker container is a lightweight, standalone, and executable package that contains all the necessary dependencies, libraries, and configurations required to run an application. It is a virtualized runtime environment that isolates the application from the underlying system, ensuring that it remains consistent and independent of the host operating system.

Docker containers are built from Docker images, which are read-only templates that include the application's source code, dependencies, and configurations. These images can be shared and reused across different environments, allowing developers to create and deploy applications consistently and reliably.

Docker containers are isolated environments with their own file system, network, and process space. They are ephemeral and can be easily created, destroyed, and replaced. Containers are portable and can be deployed across different environments, including development, testing, and production. They can also be scaled horizontally by creating multiple instances of the same container.

MongoDB Community Installation With Docker

The official MongoDB Community image allows you to run MongoDB Community Edition as a Docker container. By leveraging the MongoDB Docker image, you can effortlessly deploy the Community Edition of MongoDB as a container. This strategy provides numerous benefits, such as accelerated deployment, streamlined management of configuration files, and the capability to test various features on multiple versions of MongoDB. To run a MongoDB Docker container, you must have Docker installed on your system.

Procedure

  1. Pull MongoDB Docker Image using the command docker pull MongoDB/MongoDB-community-server
  2. You have to run the MongoDB docker Image as a container by this command docker run --name mongo -d mongodb/MongoDB-community-server:latest
  3. To install a specific version of MongoDB, specify the version after the: in the Docker run command.
  4. To check the status of the Mongodb docker container, run docker container ls. When you run the docker container ls command, the output provides information about the running container, including its Container ID, the Docker Image it is running, the Command that started the container, the date and time it was created, its current Status, any mapped Ports, and its Names.
  5. Connect to the MongoDB Deployment using Mongosh by opening a container instance of Mongosh and connect to the deployment using the command docker exec -it mongo mongosh.
  6. To validate, run the Hello command by :

The result of this command returns a document describing your MongoDB docker deployment.

MongoDB with Docker

Prerequisites

To run the instructions provided for learning MongoDB docker container, you will need to have Docker Desktop installed on your computer. You can refer to the Docker website to find the installation instructions for your specific operating system.

Running MongoDB in a Docker Container

To start a MongoDB docker container, you can use this command that involves setting a variable for the version of MongoDB you want to use.

The provided command will initiate a Docker Mongodb server, which will be version 6.0 and based on Red Hat UBI, in a detached mode (i.e., background process). It is recommended to use a tag for specifying the MongoDB version to maintain consistency. If you need to access the MongoDB server from a locally running application, you will need to expose a port using the "-p" argument. By following the above-mentioned method, you can connect to your MongoDB instance at mongodb://localhost:27017. You can test the connection using Compass, MongoDB's GUI for data visualization and analysis. It is important to note that any data that is generated during the lifespan of the container will be deleted once the container is removed. This can be done using the Docker stop and rm commands.

If you stop and restart the MongoDB docker container, the data in the Docker MongoDB Image that you added previously will still be available.

One way to run MongoDB and your application together when running the application inside a container is by using a shared Docker network. This can be achieved by specifying the --network flag. In this way, other containerized applications in the network can connect to MongoDB using mongodb://mongodb:27017.

You can create a root user for your MongoDB docker instance by setting the environment variables MONGO_INITDB_ROOT_USERNAME and MONGO_INITDB_ROOT_PASSWORD. These variables will be used to create a root user with the specified username and password, giving them full administrative privileges. Remember that you can customize the commands by combining these flags to match your requirements.

Connect to MongoDB Using Another Docker Container

In some cases, when an application is running inside a Docker container with MongoDB, it may be necessary to establish a connection to a database that is running outside of that Docker Mongodb container. To do this, it is recommended to use environment variables to set the connection string. This allows for flexibility when running the same Docker MongoDB container in different environments, such as production or development. Depending on the environment, the connection string can be set to different values, such as a MongoDB Atlas instance for production or a local MongoDB instance for development. When running a Docker container with an application that needs to connect to a database, the connection string can be provided as an environment variable in the "docker run" command. By utilizing environment variables, you can establish a connection to any Docker MongoDB instance, whether it's running locally or on the cloud, from within your application that's operating inside a container.

MongoDB with Docker Compose

Docker Compose can be used to start and stop an application and a MongoDB docker container together if they are running on the same machine. Docker Compose is ideal for development or testing environments where the full features of MongoDB Enterprise or MongoDB Atlas are not required.

To define all the MongoDB docker containers that make up the application in a docker-compose.yaml file, including a MongoDB server as one of the containers. For example:

Then, from the directory where the docker-compose.yaml file resides, run the docker-compose up command to start both Docker Mongodb containers at once. This is useful for development or testing environments where you don’t need the full functionality of MongoDB Enterprise or MongoDB Atlas.

Managing MongoDB Using Container

To manage and access your MongoDB server, as well as import and export data, you can create a separate MongoDB docker container specifically for running CLI tools.

  1. For opening the mongo shell session to the Atlas server, use the following command

Here you need the specific cluster URL. 2. To use mongoexport to export a collection to a JSON file, we can use this command

Here we are using the command from a separate MongoDB container and we are assuming that the collection name is "users". 3. To import data using MongoDB docker we use mongoimport. An example command is

Server Configuration and Security

To configure the server for your MongoDB docker container, you can modify MongoDB's default configurations by using the --config flag and specifying the location of a configuration file in YAML format. Here is an example command to specify a custom configuration file location:

To increase security, you can implement authentication in your MongoDB docker containers. This will prevent unauthorized users from accessing your database.

To add an authenticated user, set the username and password using environment variables during container creation. Use the -e flag to specify the environment variables

MONGODB_INITDB_ROOT_USERNAME and MONGODB_INITDB_ROOT_PASSWORD:

This code will start the MongoDB database using the user account "sample-db-User", which will have root privileges. It's important to choose a secure password for the root user, and you can do so by passing the location of a secrets file as the value for the environment variable MONGODB_INITDB_ROOT_PASSWORD_FILE. By doing so, your password will not be visible when inspecting the container environment variables using the "docker inspect" command. To start MongoDB docker using your username and password, use the following command:

Benefits of Using MongoDB with Docker

Using Mongodb Docker containers offers various benefits for software developers:

  1. Firstly, Docker MongoDB ensures consistency among team members as everyone is working with the same runtimes and configurations. This makes deployment smoother as the production environment is consistent with the development environment.
  2. Secondly, Docker containers are lightweight and require fewer resources than virtual machines.
  3. Finally, changes made to the Docker MongoDB container file system are destroyed when the container is terminated, providing a fresh environment every time the container starts.

MongoDB Atlas with Docker

The most effective way to incorporate Docker and MongoDB is to use a containerized application that connects to MongoDB Atlas. MongoDB Atlas provides a Database-as-a-Service and offers a free tier, which is ideal for development purposes. The free tier enables sharing of a database among team members or having a unique test database for each team member. The application can run in containers to guarantee uniformity across all environments. To connect to MongoDB, the application can use a connection string that is specified in an environment variable. MongoDB Atlas makes it simple to connect different microservices that make up your system to a single shared database. In addition to this, MongoDB Atlas also provides the benefits of running a MongoDB docker cluster without the burden of configuring, setting up, and managing a replica set.

FAQs

Q. What is Docker?

A. Docker is a containerization platform that enables developers to package and deploy their applications in portable, lightweight containers.

Q. How can you run the MongoDB docker container?

A. You can run the MongoDB docker container by using the docker run command with the appropriate flags and settings, such as specifying the container name, port mappings, and volume mounts.

Q. How can you initialize a MongoDB docker container with a root user?

A. You can initialize a MongoDB docker container with a root user by setting the MONGO_INITDB_ROOT_USERNAME and MONGO_INITDB_ROOT_PASSWORD environment variables during container creation.

Q. How can you manage your MongoDB server or access your data if you are using Docker?

A. You can use a second MongoDB container from which you will run the necessary CLI tools.

Q. What are the benefits of using Docker MongoDB?

A. Some benefits of using MongoDB docker include consistency, lightweight containers, and ephemeral file systems that ensure a fresh environment at every start. Additionally, using MongoDB Atlas makes it easy to connect all the various microservices that compose your system to the same shared database.

Conclusion

  1. In conclusion, using a Docker MongoDB container provides many benefits for software developers.
  2. With Docker, you can ensure consistency across all environments, reduce deployment friction, and easily manage MongoDB docker configurations.
  3. Additionally, using MongoDB Atlas as the database-as-a-service offering eliminates the need for setting up and managing a replica set.
  4. By following best practices such as using environment variables for connection strings and adding authentication for data security, MongoDB and Docker can work together seamlessly to provide a powerful and efficient solution for managing and deploying databases.