We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 13
2vsina, 1152 Using MongoD8 with Docker - Earthly Slog
ee 1'(01') eae
ee
‘
>
of
Using MongoDB with Docker
a
Soumi
Bardhan
Soumi
Bardhan
Docker /ittps://www.docker.com/) is a powerful development platform that enables users to containerize software,
‘These containers can be run on any machine, as well as in a public or private cloud. Thanks to Docker’s lightweight
runtime and ability to run processes in isolation, multiple containers can run at the same time on the same VM or
server.
‘MongoDB futtns://nwwmongodb.com/ is a NoSQL database service with seamless performance and options for
scaling, It uses a JSON-like storage model and doesn't require a predefined database schema. In the real world,
much data is unstructured—it doesn't follow a specific schema, NoSQL databases are useful for storing such data.
You can just input the data, and new fields will be created. You can also leave fields empty in situations where a lot
of data is missing.
MongoDB can be run in a Docker container. There is an official image (httns://hub.docker.com/_/mongo) available on
Docker Hub containing the MongoDB community edition, used in development environments. For production,
you may custom-build a container with MongoDB's enterprise version.
Ifyou want to use your MongoDB database across several machines, using Docker containers for hosting
MongoDB is a great approach — you can easily create new isolated instances. Furthermore, during development, it
is easier to start a Docker instance than manually configure a server. If you are developing multiple applications,
you can start multiple containers together using a docker-conpose.yanl file.
In this article, you'll learn the best practices for running a MongoDB container. You'll also learn how to host a
imple Flask (httns://palletsprojects.com/p/fask/ app and how to use Docker volumes to persist data in a Docker
container.
Docker Components
hitpsiiearthy.deviblogimongodb-docker! ans2aiiza, 19152 Using MongoO8 witn Docker Earthly Blog
Before diving into implementation details, let's take a moment to introduce some of Docker’s basic concepts. In a
nutshell, Docker containers are stand-alone pieces of software that encapsulate everything needed to run some
code, files, dependencies, configurations, and so forth.
The Docker daemon, dockerd , manages Docker containers and handles requests via the Docker Engine API.
Implementing MongoDB in Docker
Now, the first thing you'll want to do to set up your implementation of MongoDB is to install Docker
(bitns:L/docs.docker.com/set-docker/), which can be done directly from your terminal. However, using Docker Desktop
(tps: wwew.docker.com /products/docker-desktop) is recommended for a seamless experience.
Running MongoDB in a Docker Container
For development, it is better to connect to an instance of MongoDB running inside a Docker container locally
(instead of a cloud-hosted instance) to save resources. You can pull the latest MongoDB image and run it in a
Docker container. For production, the application can connect to a cloud-hosted database using the MongoDB
Alas (https//w. mongodh com/cloud/atlas/) or MongoDB Enterprise Server
(@tns./ew.mansod.com/Ary/dovnload /enterarse).
In development, you will use Docker to host a MongoDB instance locally. Start by pulling the image for the
‘MongoDB version you want by specifying the tag accordingly:
You can start a MongoDB server running the latest version of MongoDB using Docker with the following
command:
This will pull the latest official image (https://hubdocker.com/ /mongo/) from Docker Hub. Adding the -¢ flag will
ensure that the Docker container runs as a background process, separate from the shell. The -p tag signifies the
port that the container port is bound back to 27017. You can connect to MongoDB on tocathost:27617
hitpsiiearthy.deviblogimongodb-docker! 232aiiza, 19152 Using MongoO8 witn Docker Earthly Blog
To change the port number,
also use the --port flag to mention the post. Using the latest image helps you avoid version bumps. Execute this to
run MongoDB on port 5200
you can change the -p flag argument to s009:27017 to use locathost:8900 . You can
or)
1se Your own port:
Alternatively, if you pulled the image specifying a version tag, run the Docker container with this command:
Then use the following command to open the MongoDB shell. Ihave used mysongo as an arbitrary container name,
though you can replace nysongo with test-nongo or any other container name of your choosing.
Your interactive MongoDB shell should look like this:
interactive MongoDB shell for container
The show dos command will display all your existing databases. Here, you have the admin, config, and local
databases, which are empty initially. For details on the different functions that are available from the shell, type
“help”. This will provide a list of some of the database methods available, including commands to display the
database's collections and information.
hitpsiearthy.devilogimongodb-tocker! ans2uisia2, 1152
Dery
Perit
mycolt.helpO
het pC
Ue)
penny
ee
pewonn
Pears
Ereoeaezer Te)
Pore to ae eee)
eee eee
Using MongoD8 with Docker - Earthly Slog
one cs
HS cS Gales se cos
sharding helpers
Steet
Beicereeeretra nt
eee or)
egeeseans
Seca
Bae
ornare
es
tec eet
Pe eeerets rarerrareens
arene nse aeons
preenarners
Peart peeeninterstoncy
rears enter aaa
Petes
result of the last Line evaluated; use to further iterate
default number of itens to display on shell
Sree
foo
You can interact with your locally hosted MongoDB instance through this shell directly from your terminal. You
can also open up the container CLI using the buttons on Docker Desktop:
hitpsiearthy.devilogimongodb-tocker!2uisia2, 1152 Using MongoD8 with Docker - Earthly Slog
To check your container logs, you can use the docker logs command followed by the name of your container:
You can also inspect MongoDB’s logs with the docker logs command:
By using the --foliow flag, the container logs will be updated on your terminal in real time.
Connecting From Another Container
Once the MongoDB server is running on Docker, you can also run the Flask app in Docker. There is a Dockerfile in
the repository fotos:/sithuh com/Soumiz/Mongo-Docker) containing a set of commands to build a Docker image and run
it. In this case, connecting both containers to a shared Docker network is a good idea. This will ensure security, as
you will not need to publish MongoDB ports to the host. To create a network and connect the MongoDB container
tot, use these command:
Your client cor
ner should join the ‘est-network , to0. Your container will be able to reference the MongoDB
container by using the URL test-nongo:27617
Persisting Data With Volumes
While running MongoDB in Docker, one of the main challenges is storage. Usually, users want to be able to
selectively persist data for containers. A good practice is to use volumes to make sure the data persists even after
the container is stopped or the Docker daemon is restarted. By default, the MongoDB image stores its data in the
hitpsiearthy.devilogimongodb-tocker! sit32aiiza, 19152 Using MongoO8 witn Docker - Earthly Blog
/data/db directory. You can mount a volume to this location to enable data persistence. Use this command to
create a container test-rongo with a Docker volume (htins://docs docker.com/storage/volumes/) named. data-vo1
‘mounted on it:
If you want to inspect your volumes, you can do so with the docker volume inspect command.
You can check out all the existing volumes to display which volumes are attached to which containers using docker
volume 1s
Configuring Your Server
If you want to change the default MongoDB configurations (https: docs mongodh com/manual/reference/configuration-
cntions/), you can use the --config flag to pass a location to a text file with configurations. The configuration file
follows the YAML format. Here is the command to specify a certain config location:
Security
You can also add authentication to your MongoDB containers to ensure data security. This will disable
unauthorized personnel from connecting to your server.
hitpsiiearthy.deviblogimongodb-docker! es2aiiza, 19152 Using MongoO8 witn Docker - Earthly Blog
Add your user account by setting the username and password using the environment variables during container
creation, Use the -e flag to specify the environment variables. wowsoos_xurTos_aooT_userNase and
MoNG008_INTTDB_ROOT_PASSWORD :
Asa result, the database will be started with the user account sanple-db-user . This new user will be granted root
privileges. As the root user will have access control over everything, it is important to provide a safe password. In
this case, you can pass the secrets file location as input to the environment variable
ocoo8_INTTO8_RoOT_PASsWORO_FILE . Your password will not be visible on using docker inspect to view the container
environment variables. To run MongoDB with Docker using your username and password, use the below code:
Flask App for Student Database Management
In this section, you will create a simple storage app where MongoDB will store records of students’ marks. To start,
you'll want to open Docker Desktop and delete the containers you just created, as you will be ereating a few more
now. Then in the Flask web app, you will add functionality for the following:
+ Adding a new record to the database
+ Viewing list of all records
‘This will help ensure that the database is working as expected. Start by cloning this GitHub repository.
‘httns//sithub,com/Soumi7/Mongo-Docker):
This repository consists of four main sections:
hitpsiiearthy.deviblogimongodb-docker! mspuis, 1152 Using MongoD8 with Docker - Earthly Slog
+ templates : The HTML page templates for different pages.
+static : The CSS files for each HTML page.
+ app.py : The Flask app endpoints are defined here, along with the functions.
+ requirenents.txt : The list of dependencies.
To access the server from your locally hosted Flask app, you will need to export a port using the -p flag:
Your MongoDB instance will be accessible on mongodb: //localhost:27017 . To visualize and analyze it with a GUI,
you can use MongoDB Compass (httys://www.mongodb com/produets/compass).
To run the Flask app, you first need to install Python—any Pythons, version (hns:/sw. python ore/downlonds/ will do.
Neat, install dependencies by running the following code in your terminal:
For ease of development, you will run the Python app outside the container and run Mongo inside one. Go ahead
and run the Python Flask app with python3 app.py now.
(flask_mongo) Es YE ET ST
eat uEne eG
* Serving Flask app ‘app' (lazy Loading)
Pear Uses asth)
Pea aCe
CRUnEOr Russ S/O ete ee Te)
Sa astr eres
Pree caesar
Ses Ber ke
be aa Ee
database {'_id': ObjectId('619cecabbb9F14c667366fa9'), ‘Name’: ‘gh', ‘grds
De eee Os Co eo ctor YA
y
Peta a SC ee
aR
PLA)
127.
304
127.0.0. EY aye see Te LS Ca ee
127.0.0. [23/Nov/2021 19:14:38] "GET /static/css/s HTTP/1.1
EY
[23/Nov/2021 19:14:36] "GET /fulllist HTTP/1.1" 200 -
ie
ee
aioe ICNP ys ters Name eater tld Pee
hitpsiiearthy.deviblogimongodb-docker! ans2yvana, 152 Using Mongo08 with Docker Earthly Blog
Using the Flask interface, you can add, update, and view records. To get started, go to localhost :5000
Student Grades Database
Add new Student
Physics
Chemisty
Maths
Student Grades Database
Fill in a new record and click on Submit Grades. This page will confirm your submission:
New submission accepted for student
‘Next, go back to the homepage and click on Get Grades of all Students. This page will show all your student
records:
hitpsiiearthy.deviblogimongodb-docker! ons2iaing, 1152 Using MongoD8 with Docker - Earthly Slog
LIST OF STUDENTS AND GRADES
‘Student Name Prysies Cchemisy Matnematies
List of students and
‘Add a few more entries and ensure that the app is working as expected. You can also edit submissions for a certain
student. After adding a few more records, your database might look like this:
sT OF STUDENTS AND GRADES
Student Name Prysies Chemisty Matnematis
List of students and grades
For this container, you did not attach a volume. So when you create a new container from the same MongoDB
image, it will start with an empty database. Go to Docker Desktop and stop the running container test-nongo . You
can also use docker stop test-nongo to stop the container from the terminal. To see the list of running containers
and their details, use docker container list . Then create another container for MongoDB from the terminal:
Now go to localhost:see¢ and click on Get Grades of all Students:
hitpsiiearthy.deviblogimongodb-docker! 10132iaing, 1152 Using MongoD8 with Docker - Earthly Slog
LIST OF STUDENTS AND GRADE:
‘Student name Prysies Chemisty Matnemeties
Empty list of al students
‘This time, you will see that all the previous data has been lost, and instead, you are starting with an empty
database. This is where volumes come in handy.
Stop the container test-nongo2 . Create a container called test-nongo-3 and attach a volume to it. Any data created
as part of the lifecycle of that container will be destroyed once the container is deleted. However, you want to
persist the data on your local machine, so go ahead and mount a volume using the -v argument:
‘Then go to locathost:5e¢@ and add some new records to the student database:
LIST OF STUDENTS AND GRADES
stucent Name Prystes ‘chemisy Mamemates
‘Student records database (Tania, Sam, and Beth)
‘When you stop this container and create a new one, you will enable the new container to use the volume of the
container and create a new container with the --voluses-fron tag followed by the name of
previous one. Stop t
the container with the volume you want to mount onto this container—in this case, test-nongo-3 :
hitpsiiearthy.deviblogimongodb-docker! 1132yvana, 152 Using Mongo08 with Docker Earthly Blog
Now, when you go to locathost 5000 , you will notice that all the data you previously added has remained intact, as
Docker attached the volume after the start. Volumes persist until you remove them with the docker votunes om
command or by using the --volunes flag when destroying a container with docker om
If your application is running inside a container itself, you can run MongoDB as part of the same Docker network
as your application using. --network . With this method, you will connect to MongoDB on songodb: //songod:27037,
from the other containerized applications in the network.
Conclusion
In this article, you hosted your MongoDB server using Docker. You created a Flask app to test if the server works
as expected, and you learned to attach volumes to your container to see how the containers behave with and
without them,
‘There are many advantages of using containers as part of your day-to-day life as a software developer. Containers
ensure consistency across operating systems, and by using them, you can ensure uniformity throughout the team.
Deploying containers is relatively easy, as your production environment and development will be consistent. By
running MongoDB in Docker, you can create new isolated containers from the same image and you can connect
the volume associated with one container to another.
Earthly tutns//easthivdev/) is an automation tool for managing all your Docker components
‘tts: //does earthy dev/ des uldes/dovker-in-eartly), images, and containers. With Earthly, you can execute all your
builds in containers and ensure uniformity across machines.
While you're here:
Earthly (htns:{/earthivdev/) is a syntax for defining your build. It works with your existing build system. Get
repeatable and understandable builds today.
categories: | Tutorials
Updated: February 22, 2022
Get notified about new articles
Email Address f
‘We won't send you spam. Unsubscribe at any time,
hitpsiiearthy.deviblogimongadb-docker! sanspang, 1152 Using MongoD8 with Docker - Earthly Slog
hitpsiiearthy.deviblogimongodb-docker! 1313