This blog was originally published in August of 2021 and updated in November of 2023.
Following the series of blogs written with the intention to describe basic operations matching Docker and open source databases, in this article, I will demonstrate how to proceed with installing MongoDB with Docker.
The first one, written by Peter Zaitsev, was Installing MySQL with Docker.
Before proceeding, it is important to double warn by quoting Peter’s article:
“The following instructions are designed to get a test instance running quickly and easily; you do not want to use these for production deployments”.
Also, a full description of Docker is not the objective of this article, though I assume prior knowledge of Docker, and also you that already have it installed and configured to move on.
Docker quickly deploys standalone MongoDB containers. If you are looking for fast deployments of both replica sets and shards, I suggest looking at the mlaunch tool.
Peter mentioned, in his article, how MySQL has two different “official” repositories, and with MongoDB, it’s the same: MongoDB has one repository maintained by MongoDB and another maintained by Docker. I wrote this article based on the Docker-maintained repository.
What are MongoDB Docker Containers?
Docker containers are small, executable, standalone packages that come with all the components—code, runtime, libraries, and system tools—necessary to run a piece of software. They provide a reliable and effective method for developing, deploying, and executing applications in a range of settings, from development to production.
When discussing MongoDB containers, we are talking about a Docker container holding MongoDB together with its particular version, customizations, and dependencies. Whether it is a production server, a test environment, or a developer’s workstation, this encapsulation makes it easier to deploy MongoDB instances in a variety of scenarios, making it more portable and scalable.
Installing the Latest Version of MongoDB
The following snippet is one example of how to initiate a container of the latest MongoDB version from the Docker repository.
docker run --name mongodb_dockerhub
-e MONGO_INITDB_ROOT_USERNAME=admin
-e MONGO_INITDB_ROOT_PASSWORD=secret
-d mongo:latest
Now, if you want to check the container status right after creating it:
docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
fdef23c0f32a mongo:latest "docker-entrypoint..." 4 seconds ago Up 4 seconds 27017/tcp mongodb_dockerhub
Connecting to MongoDB Server Docker Container
Having the container installed up and running, you will notice that no extra step or dependency installation was previously required, apart from the docker binaries. Now, it is time to access the container MongoDB shell and issue a basic command like “show dbs”.
docker exec -it mongodb_dockerhub mongo -u admin -p secret
MongoDB shell version v4.2.5
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("89c3fb4a-a8ed-4724-8363-09d65024e458") }
MongoDB server version: 4.2.5
Welcome to the MongoDB shell.
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
> exit
bye
It is also possible to connect to the containerized MongoDB using a host mongo shell. On the docker ps output, the container id has a field that informs its port mapping, and then it is a simple connection using that port.
In the below example, we connected to the mongodb_dockerhub36. It’s up and running locally on port 27017 but mapped to the host 27018 port:
docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
60ffc759fab9 mongo:3.6 "docker-entrypoint..." 20 seconds ago Up 19 seconds 0.0.0.0:27018->27017/tcp mongodb_dockerhub36
Hence, the mongo shell connection string will be executed against the external IP and port 27018
mongo admin -u admin --host 172.16.0.10 --port 27018 -psecret
Managing MongoDB Server in Docker Container
The following commands will demonstrate basic management operations when managing a MongoDB container.
- Starting the container and checking the Status
docker start mongodb_dockerhub
docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
fdef23c0f32a mongo:latest "docker-entrypoint..." 47 minutes ago Up 2 seconds 27017/tcp mongodb_dockerhub
- Stopping the container and checking the Status
docker stop mongodb_dockerhub
docker ps
CONTAINER ID IMAGE COMMAND
- Taking a look at the MongoDB log entries
docker logs mongodb_dockerhub
...
about to fork child process, waiting until server is ready for connections.
forked process: 25
2020-04-10T14:04:49.808+0000 I CONTROL [main] ***** SERVER RESTARTED *****
2020-04-10T14:04:49.812+0000 I CONTROL [main] Automatically disabling TLS 1.0, to f
...
Passing Command Line Options to MongoDB Server in Docker Container
It is also possible to define the instance’s parameters when launching the MongoDB container. In the example below, I will show how to set the WiredTiger cache.
docker run --name mongodb_dockerhub
-e MONGO_INITDB_ROOT_USERNAME=admin -e MONGO_INITDB_ROOT_PASSWORD=secret
-d mongo:latest --wiredTigerCacheSizeGB 1.0
Running Different MongoDB Server Versions in Docker
Another possibility is getting two MongoDB containers running in parallel but under different versions. The below snippet will describe how to build that scenario
- Launching a 4.0 container
docker run --name mongodb_dockerhub40
-e MONGO_INITDB_ROOT_USERNAME=admin -e MONGO_INITDB_ROOT_PASSWORD=secret
-d mongo:4.0
- Launching a 3.6 container
docker run --name mongodb_dockerhub36
-e MONGO_INITDB_ROOT_USERNAME=admin -e MONGO_INITDB_ROOT_PASSWORD=secret
-d mongo:3.6
- Checking the container’s status
docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
e9f480497f2d mongo:3.6 "docker-entrypoint..." 32 seconds ago Up 32 seconds 27017/tcp mongodb_dockerhub36
3a799f8a907c mongo:4.0 "docker-entrypoint..." 41 seconds ago Up 41 seconds 27017/tcp mongodb_dockerhub40
If for some reason you need both containers running simultaneously and access them externally, then use different port mappings. In the below example, both MongoDB’s containers are deployed on the local 27017 port, nevertheless, I am setting different external port maps for each one.
- MongoDB 4.0 mapping the port 27017
docker run --name mongodb_dockerhub40
-p 27017:27017
-e MONGO_INITDB_ROOT_USERNAME=admin -e MONGO_INITDB_ROOT_PASSWORD=secret
-d mongo:4.0
- MongoDB 3.6 mapping the port 27018
docker run --name mongodb_dockerhub36
-p 27018:27017
-e MONGO_INITDB_ROOT_USERNAME=admin -e MONGO_INITDB_ROOT_PASSWORD=secret
-d mongo:3.6
- Checking both Container’s status
docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
78a79e5606ae mongo:4.0 "docker-entrypoint..." 3 seconds ago Up 2 seconds 0.0.0.0:27017->27017/tcp mongodb_dockerhub40
60ffc759fab9 mongo:3.6 "docker-entrypoint..." 20 seconds ago Up 19 seconds 0.0.0.0:27018->27017/tcp mongodb_dockerhub36
There are a lot of extra details on Docker’s MongoDB Hub page and you will find more options to use on your MongoDB Docker deployment. Enjoy it!
Advantages of Using Docker for MongoDB
MongoDB Docker containers offer a more efficient, consistent, and scalable way to run MongoDB instances, and they offer several advantages over typical MongoDB installations in the following ways:
Isolation and portability: Because MongoDB containers have their own file system, libraries, and network configurations, they are isolated from the host system. Because of this isolation, the MongoDB instance is guaranteed to operate consistently no matter what host system is used. In conventional setups, achieving this degree of isolation is difficult.
Uniformity throughout environments: MongoDB instances are housed in a uniform environment thanks to MongoDB containers. This consistency minimizes the “it works on my machine” issue by guaranteeing that what functions on a developer’s laptop will act similarly in a staging or production environment.
Dependency management: MongoDB containers bundle all required dependencies, removing the possibility of conflicts with the host system’s other programs or libraries. Managing and resolving dependencies in a typical MongoDB installation can be difficult and error-prone.
Scalability and resource management: MongoDB containers and other containers are very scalable. Multiple MongoDB containers can be quickly spun up to divide workloads, establish replica sets, and sharded clusters. A conventional MongoDB installation’s scaling can be more difficult.
Easy to use: Setting up MongoDB containers is a simple procedure, as you can specify the desired state of your MongoDB containers using Docker Compose or Kubernetes, and then let the orchestration tools take care of the deployment.
Troubleshooting and Common Issues for MongoDB Docker Installation
Although deploying MongoDB in a Docker container has many advantages, there are occasionally typical challenges. Here, we’ll explore some of these issues and provide troubleshooting guidance.
MongoDB container fails to start: If your MongoDB container doesn’t start, check that the Docker command you are using to launch it is correct. Verify image names, ports, and environment variables one more time and examine container logs.
Connection issues: Make sure your application is connecting to the correct hostname and port if you are experiencing issues with MongoDB connections in Docker. Verify network settings to ensure appropriate communication, as well as the accuracy of the credentials before utilizing authentication.
Data persistence: By configuring data persistence, you can prevent data loss in the case that a MongoDB container is stopped or removed. Use Docker volumes or host bind mounts to safeguard data.
Resource allocation: Optimize the performance of MongoDB containers by modifying resource distribution. Adjust Docker’s CPU and RAM limits to improve slow performance.
And if you are in need of some assistance from fellow MongoDB users, there are lots of resources and communities you can participate in:
- Look through the MongoDB community forums for advice, solutions, and group problem-solving with experienced users.
- The Docker community forum is a good place to find answers on containerization-related issues and is a vital resource for assistance with Docker-related difficulties.
- Look through the issues section of the MongoDB GitHub repository to find and discuss any MongoDB Docker image problems.
- The Percona Community Forum is where users, developers, and database professionals gather to discuss and share information about database management solutions.
Best Practices for Managing MongoDB Containers
Maintaining your database system’s scalability, security, and performance requires effective MongoDB container administration. In order to optimize your MongoDB deployment, it’s essential that you adhere to best practices in a number of vital areas.
Security considerations: Securing your MongoDB containers is a top priority. To protect your data, put authentication and access control systems in place. Strong security features are provided by MongoDB, including authentication, encryption, and role-based access control (RBAC). Set parameters to prevent unwanted access and safeguard private data, and to protect yourself against known vulnerabilities, keep your MongoDB container images and software updated with the newest security updates.
Container orchestration options: To handle MongoDB containers at scale, think about utilizing container orchestration systems like Docker Swarm or Kubernetes. These solutions provide high availability and resource optimization while making deployment, scaling, and load balancing simpler. Container orchestration is especially helpful when dealing with a large number of containers, as it automates routine tasks to maintain system integrity.
Regular maintenance and updates: To keep your MongoDB containers operating properly, make sure you regularly update the underlying container image as well as the database software because performance enhancements, security patches, and bug fixes are frequently included in updates. Monitoring your containers for indications of resource limitations or performance problems is another aspect of routine maintenance, and to make sure your MongoDB containers can effectively manage a range of workloads, set up warnings and automated scaling.
Run MongoDB Your Way Percona
Percona offers source-available, enterprise-grade software and services to run MongoDB at peak performance, on any infrastructure. No licensing fees, expensive support contracts, or vendor lock-in.
Learn more about Percona for MongoDB
FAQs
Is it advisable to deploy MongoDB within a Docker container?
In some cases, it can be advisable to use a Docker container to deploy MongoDB, especially if you are running it on-premises. Docker containers are a good option for MongoDB installations because of their benefits, which include isolation, portability, and scalability. Before making a choice, it is crucial to consider the requirements and the particular use case into account.
Can I run multiple MongoDB containers on the same host using Docker?
Yes, you can use Docker to run multiple MongoDB containers on the same host. You can create numerous isolated MongoDB instances for different applications or workloads because each container runs independently.