---
title: "How to Deploy and Manage a Docker MongoDB Container"
description: "Got a Docker MongoDB container to deploy, but not sure how to? Well, you're in for a treat! Learn how to deploy and manage a Docker MongoDB container in this tutorial!"
canonical: "https://adamtheautomator.com/docker-mongodb/"
---

# How to Deploy and Manage a Docker MongoDB Container

> Got a Docker MongoDB container to deploy, but not sure how to? Well, you're in for a treat! Learn how to deploy and manage a Docker MongoDB container in this tutorial!

Source: https://adamtheautomator.com/docker-mongodb/

---

ATA Learning

Tap to hide

[

ATA Learning

](/)

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Search for:  

*   [](https://twitter.com/adbertram)
*   [](https://github.com/Adam-the-Automator)
*   [](https://www.linkedin.com/company/adam-the-automator-llc)
*   [](/feed/)

![How to Deploy and Manage a Docker MongoDB Container](https://adamtheautomator.com/wp-content/uploads/2021/11/How-to-Deploy-and-Manage-a-Docker-MongoDB-Container.jpg)

# How to Deploy and Manage a Docker MongoDB Container

[![](https://secure.gravatar.com/avatar/2788bb1a3f735603f81eca51d68daec56a9d97e805a10268fb2c20afcc76b81b?s=192&d=mm&r=g)Nicholas Xuan Nguyen](https://adamtheautomator.com/author/nicholas-xuan-nguyen/)23 November 20218 min. read

Categories: [IT Ops](/category/it-ops/)

Tags:[Docker](/tag/docker/)[MongoDB](/tag/mongodb/)

Table of Contents

*   [Prerequisites](#prerequisites)
*   [Downloading the Docker MongoDB Image](#downloading-the-docker-mongodb-image)
*   [Deploying a Docker MongoDB Container](#deploying-a-docker-mongodb-container)
*   [Attaching the Docker MongoDB Container to Bash Shell](#attaching-the-docker-mongodb-container-to-bash-shell)
*   [Creating an Administrative MongoDB User](#creating-an-administrative-mongodb-user)
*   [Creating a MongoDB Database](#creating-a-mongodb-database)
*   [Restarting the Docker MongoDB Container](#restarting-the-docker-mongodb-container)
*   [Conclusion](#conclusion)

[MongoDB](https://www.mongodb.com/) is a popular, open-source document database that provides high performance and great flexibility. But have you tried to [containerize](https://www.docker.com/resources/what-container/) a MongoDB database for your projects? If not, then you’re in for a treat!

In this tutorial, you’ll learn how to deploy, secure, and manage MongoDB effectively with Docker. So read on and become your own master of deploying Docker MongoDB containers!

## Prerequisites

This tutorial comprises hands-on demonstrations. To follow along, be sure you have the following:

*   An Ubuntu machine – This tutorial uses [Ubuntu 20.04](https://adamtheautomator.com/install-ubuntu/) LTS

Related:[How to Install Ubuntu 20.04 \[Step-by-Step\]](https://adamtheautomator.com/install-ubuntu/)

*   A user with `sudo` permission
*   [Docker](https://docs.docker.com/engine/install/ubuntu/) – This tutorial uses Docker 20.10.9

Related:[How to Install and Use Docker on Ubuntu (In the Real World)](https://adamtheautomator.com/docker-ubuntu/)

## Downloading the Docker MongoDB Image

Before you can deploy and manage a Docker MongoDB container, you first need to download a MongoDB image from the Docker Hub so you can run the MongoDB container locally.

Run the `docker` command below to download the MongoDB Community Edition(CE) image (`pull mongo`), which [Docker Hub](https://hub.docker.com/_/mongo) is hosting. The latest version of this image at the time of writing is 4.2.

```bash
sudo docker pull mongo
```

As you can see below, the command automatically pulls the latest version of the image and tags it as **latest**.

![Pulling mongo image](https://adamtheautomator.com/wp-content/uploads/2021/11/image-301.png)

Pulling mongo image

Now run the `docker images` command below to list all images available on your server.

```bash
sudo docker images
```

Below, you can see the MongoDB image tagged as **latest**.

![Listing all Docker images](https://adamtheautomator.com/wp-content/uploads/2021/11/image-302.png)

Listing all Docker images

## Deploying a Docker MongoDB Container

From the MongoDB image you downloaded, you can now deploy a MongoDB container. You’ll initialize your MongoDB container with the mongo executable, create a data directory. You’ll then define the mapping between the Docker container’s data area and the host machine.

1\. Run the `mkdir` command below to create a data directory named `mongodata` to store the MongoDB database and logs.

```bash
sudo mkdir -p /mongodata
```

2\. Next, execute the `docker run` command below to create a container given the name `mymongo`. In addition, the container is started with an interactive pseudo-TTY (`-it`), in the event that output should be shown when starting the container.

Finally, the newly created directory _mongodata_ is bound (`-v`) to the internal directory, _/data/db_. The `-d` option starts the container in the [detached mode](https://www.freecodecamp.org/news/docker-detached-mode-explained/), so it runs as a background process and returns the console output upon creation.

The system automatically creates the _/data/db_ directory when you run the container to store data of the changes you make in the container. This directory runs in a similar mode to read-only and enables persistent data storage on the host system.

```bash
sudo docker run -it -v mongodata:/data/db --name mymongo -d mongo
```

Once the command completes successfully, you’ll see an output like the one below.

![Deploying MongoDB Container](https://adamtheautomator.com/wp-content/uploads/2021/11/image-303.png)

Deploying MongoDB Container

3\. Finally, run the [`docker ps`](https://docs.docker.com/engine/reference/commandline/ps/) command below to identify the container’s ID and check its status. The `docker ps` command displays all information about the currently running container.

> _The `docker ps` command is comparable to the regular [`ps`](https://www.geeksforgeeks.org/ps-command-in-linux-with-examples/) command in Linux._

```bash
sudo docker ps
```

In the output shown below, you can see a **Ports** section that lists all the ports assigned to the container for listening to incoming connections.

In this example, port **27017** is mapped to the host. The below output indicates you can access the MongoDB instance on this container via _localhost:27017_ from the host.

![Checking Docker MongoDB Container Status](https://adamtheautomator.com/wp-content/uploads/2021/11/image-304.png)

Checking Docker MongoDB Container Status

> _Perhaps you want to see the log file of the `mymongo` container to determine what happened on your mongo database/instance when something went wrong with it. If so, run the `docker logs` command, like this: `sudo docker logs docker-container`. Replace `docker-container` with the name of your Docker container name._

![Reading Docker Container Log File](https://adamtheautomator.com/wp-content/uploads/2021/11/image-305.png)

Reading Docker Container Log File

## Attaching the Docker MongoDB Container to Bash Shell

You’ve just deployed a Docker MongoDB container, but how do you manage it? Do so by attaching the Docker container to the Bash shell with the [`docker exec`](https://docs.docker.com/engine/reference/commandline/exec/) command first.

Attaching your container to the Bash shell is crucial since the container is currently running in detached mode (running in the background). And if the container runs in the background, the container will neither receive any input nor display output.

Run the `docker exec` command [](https://manpages.ubuntu.com/manpages/lunar/en/man1/docker-exec.1.html)below to attach your container (`mymongo`) to the Bash shell.

```bash
sudo docker exec -it mymongo bash
```

When the command completes, your prompt will change to something like the one below. The unique alphanumeric number (**77782fa95314**) is the container ID.

> _Container IDs are essential to avoid naming conflicts and effectively identify containers between hosts, so try not to change them._

![Attaching Docker MongoDB Container to Bash Shell](https://adamtheautomator.com/wp-content/uploads/2021/11/image-306.png)

Attaching Docker MongoDB Container to Bash Shell

Now run the `mongo` command without any [arguments](https://docs.mongodb.com/manual/reference/command/) to log into the [MongoDB shell](https://docs.mongodb.com/v4.4/mongo/) in the container (mymongo). The MongoDB shell is where you run your mongo queries/commands.

> _Once you are in the container, you can run any command without the `sudo` prefix since you’re now a root user inside the container. Every change you make in the container will not affect your host system._

```bash
mongo
```

By looking at the prompt shown below, you can tell that you’re now in the MongoDB shell.

![Logging in to the MongoDB shell](https://adamtheautomator.com/wp-content/uploads/2021/11/image-307.png)

Logging in to the MongoDB shell

> _If you prefer to see all available commands in the MongoDB shell, run the `help` command, as shown below._

![Listing Available Commands in MongoDB Shell](https://adamtheautomator.com/wp-content/uploads/2021/11/image-308.png)

Listing Available Commands in MongoDB Shell

## Creating an Administrative MongoDB User

After you’ve deployed a MongoDB server inside a Docker container, you’ll now create an administrative MongoDB user. An administrative user lets you connect to the MongoDB server and manage databases.

1\. Log in to MongoDB shell again and run the [`use`](https://docs.mongodb.com/manual/tutorial/manage-users-and-roles/) command below to first switch to the `admin` database. Doing so provides the administrative user with the right permissions to manage the databases.

```bash
use admin
```

![Switching to the Admin Database](https://adamtheautomator.com/wp-content/uploads/2021/11/image-309.png)

Switching to the Admin Database

Copy and paste the following code in the MongoDB prompt to create an administrative user.

The code below uses the [`db.createUser()`](https://docs.mongodb.com/manual/reference/method/db.createUser/) method [](https://docs.mongodb.com/manual/reference/method/db.createUser/)to create a user with administrative roles. The username (`user`) and password (`pwd`) below are hardcoded, which you can change based on your preference.

```bash
# Create an administrative user
db.createUser(
{
	# Sets the username for the administrative user
	user: "ata",
	# Sets the password for the administrative user
	pwd: "password123",
	# Sets the roles for the administrative user
	roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
```

If the code works, you’ll get a message like the one below in your MongoDB prompt.

![Creating an Administrative New User](https://adamtheautomator.com/wp-content/uploads/2021/11/image-310.png)

Creating an Administrative New User

3\. Run the [`quit()`](https://docs.mongodb.com/manual/reference/method/quit/) query below to exit the MongoDB shell.

```bash
quit()
```

4\. Finally, run the following `mongo` command to test the administrative user you created (`ata`) by connecting to the MongoDB server. Enter the password for the administrative user when prompted.

```bash
mongo -u ata -p --authenticationDatabase admin
```

As you see below, the MongoDB server prints out the MongoDB server version if you connect to the server successfully.

![Connecting to the MongoDB Server ](https://adamtheautomator.com/wp-content/uploads/2021/11/image-311.png)

Connecting to the MongoDB Server

> _Perhaps you want to test the administrative user further. If so, run the commands below to show all the users in the database._

```bash
use admin
show users
```

Below, you can see the administrative user you created is in the list.

![Listing Users in Database](https://adamtheautomator.com/wp-content/uploads/2021/11/image-312.png)

Listing Users in Database

## Creating a MongoDB Database

Managing a Docker MongoDB container wouldn’t be complete without creating a database. You’ll create a new MongoDB database that you’ll store data into via MongoDB shell.

1\. From within an interactive session within the Docker container, run the `show dbs` command below to list all databases in your server.

```bash
show dbs
```

Below, you can see an admin database, a config database, and a local database. The MongoDB shell creates these databases by default in every MongoDB server.

![Listing all MongoDB Databases](https://adamtheautomator.com/wp-content/uploads/2021/11/image-313.png)

Listing all MongoDB Databases

2\. Next, run the [`use`](https://docs.mongodb.com/manual/tutorial/use-database-commands/) command below [](https://docs.mongodb.com/manual/tutorial/use-database-commands/)to create a new database. Replace `<database_name>` with the database name of your choice. But for this example, the database is named `linux`.

> _The `use` query switches the current database to the one you specify if it exists. If not, the `use` query creates a new database and automatically switches to it._

```bash
use <database_name>
```

![Creating a new MongoDB Database](https://adamtheautomator.com/wp-content/uploads/2021/11/image-314.png)

Creating a new MongoDB Database

3\. Rerun the `show dbs` command as you previously did (step one) to see if the database you created exists.

```powershell
show dbs
```

Still don’t see the newly created database (linux) on the list? MongoDB builds the database only when you store data in it for the first time. The data may be in the form of a [collection](https://docs.mongodb.com/manual/reference/glossary/#std-term-collection) or even a [document](https://docs.mongodb.com/manual/reference/glossary/#std-term-document).

![Listing all MongoDB Databases](https://adamtheautomator.com/wp-content/uploads/2021/11/image-315.png)

Listing all MongoDB Databases

4\. Now copy/paste the code below to the MongoDB shell and press **Enter**.

The code below creates a new collection named `linux_version`, which you can change to which name you prefer. The collection contains data in key:value pairs format.

```bash
# Using insertOne method to insert data
db.linux_version.insertOne(
	# Key:value pairs to insert to the database
	{ "debian" : "11",
	"ubuntu" : "20.04",
	"rocky linux" : "8.4",
	"alma linux" : "8"
	}
)
```

In the output below, you can see the `linux_version` collection is created and comes with an **ObjectID**.

![Showing collection with its ID](https://adamtheautomator.com/wp-content/uploads/2021/11/image-316.png)

Showing collection with its ID

5\. Run the [`show collections`](https://docs.mongodb.com/manual/reference/mongo-shell/) command to see a list of collections and see if the new collection `linux_version` exists.

```bash
show collections
```

You can see below that you’ve successfully created the **linux\_version** collection.

![Showing List of Collections](https://adamtheautomator.com/wp-content/uploads/2021/11/image-317.png)

Showing List of Collections

6\. Finally, run the command below to view and confirm the data you inserted in the `linux_version` collection is correct. The [pretty()](https://docs.mongodb.com/manual/reference/method/cursor.pretty/) method lets you view the data in a human-readable format.

```docker
db.linux_version.find().pretty()
```

> _If you ever modify the data in the database, use the [`Update()`](https://www.guru99.com/mongodb-update-document.html) method._

You can see the output below is in a much readable format.

![Viewing Data from MongoDB Database](https://adamtheautomator.com/wp-content/uploads/2021/11/image-318.png)

Viewing Data from MongoDB Database

## Restarting the Docker MongoDB Container

By now, you have a successfully running Docker MongoDB container. But what if you no longer have any use for the container, or what if it’s not working? A couple of Docker commands can help to stop, restart, and even remove a MongoDB Docker container.

1\. Run the [`docker ps`](https://docs.docker.com/engine/reference/commandline/ps/) command below to list all running containers.

```bash
sudo docker ps
```

Note the name and container ID of the container you wish to stop, restart or remove, as shown below.

![Showing all running docker containers](https://adamtheautomator.com/wp-content/uploads/2021/11/image-319.png)

Showing all running docker containers

2\. Next, run either of the `docker stop` commands below to stop a running MongoDB container.

```bash
sudo docker stop mymongo
sudo docker stop container-ID
```

3\. Rerun the `docker ps` command as you previously did (step one) to check if the container has shut down.

```bash
sudo docker ps
```

As you can see below, the container is not in the list of running containers, which indicates you’ve successfully stopped the container.

![Listing all Containers](https://adamtheautomator.com/wp-content/uploads/2021/11/image-320.png)

Listing all Containers

4\. Now run either of the `docker start` commands below if you decide to restart a container.

```bash
sudo docker start mymongo
sudo docker start container-ID
```

5\. Finally, rerun the `docker ps` command to see if the container is running.

```bash
sudo docker ps
```

> _Perhaps you have no further use for a container. If so, you must stop the container first and run the `rm` command to remove a container, like this: `sudo docker container rm mongodb`. Similar to the previous examples, replace `mongodb` with either the container name or container ID._

## Conclusion

In this tutorial, you’ve learned how to deploy and manage a Docker MongoDB container by creating an administrator user to create a database and store data into it. You’ve realized that you can stop, restart and remove containers that you no longer need to keep your Docker images clean.

Related:[Keep Your Docker Images Manageable with Docker Image Prune](https://adamtheautomator.com/docker-image-prune/)

Deploying and managing MongoDB with Docker is the first step towards taking advantage of containerization technology and reducing the overhead. Why not use this first step to explore [MongoDB](https://docs.mongodb.com/manual/tutorial/install-mongodb-enterprise-with-docker/) more and see how a Docker MongoDB container can help with your projects?

Share this article

[Share on X](https://twitter.com/intent/tweet?url=https%3A%2F%2Fadamtheautomator.com%2Fdocker-mongodb%2F&text=How%20to%20Deploy%20and%20Manage%20a%20Docker%20MongoDB%20Container)[Share on Facebook](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fadamtheautomator.com%2Fdocker-mongodb%2F)[Share on LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fadamtheautomator.com%2Fdocker-mongodb%2F)

## Related Posts

![](https://adamtheautomator.com/wp-content/uploads/2023/12/buildah.jpg)

### [Building OCI Images with Buildah](/buildah/)

Master the art of crafting OCI images with buildah for seamless containerization—flexible, efficient, and tailored to your container needs.

![](https://adamtheautomator.com/wp-content/uploads/2023/06/mongodb-replica-set.jpg)

### [Guide to Set up Replica Sets on MongoDB Servers](/mongodb-replica-set/)

Learn how to effectively setup a MongoDB replica set and ensure data is reliably stored in redundant locations for data security.

![](https://adamtheautomator.com/wp-content/uploads/2023/06/docker-raspberry-pi.jpg)

### [How to Install Docker on Raspberry Pi 4](/docker-on-raspberry-pi/)

Excerpt: Learn how to get started with installing Docker on Raspberry Pi 4 and offload development to a small flexible system.

## Categories

*   [IT Ops](/category/it-ops/)
*   [Cloud](/category/cloud/)
*   [DevOps](/category/devops/)
*   [Home Ops](/category/home-ops/)
*   [Information Security](/category/infosec/)
*   [Software Development](/category/software-development/)

## Site

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Copyright 2026© ATA Learning | [Privacy Policy](/privacy/)
