Running MongoDB in Docker: A Practical Guide
In this blog post, we’ll walk through the process of running MongoDB in a Docker container. This approach offers flexibility, ease of deployment, and consistency across different environments. Let’s dive in!
Prerequisites:
- Docker installed on your machine
- Basic knowledge of Docker commands
Step 1: Pull the MongoDB Image
First, let’s pull the official MongoDB image from Docker Hub:
docker pull mongo
This command downloads the latest MongoDB image to your local machine.
Step 2: Run MongoDB Container
Now, let’s run a MongoDB container
docker run -d --name my-mongodb -p 27017:27017 mongo
Let’s break down this command:
-d
: Runs the container in detached mode--name my-mongodb
: Names our container "my-mongodb"-p 27017:27017
: Maps the container's port 27017 to our host's port 27017mongo
: Specifies the image to use
Step 3: Verify the Container is Running
Check if your container is running:
docker ps
You should see your “my-mongodb” container in the list.
Step 4: Connect to MongoDB
To interact with your MongoDB instance, you can use the mongo shell within the container:
docker exec -it my-mongodb mongosh
This command opens an interactive mongo shell where you can run MongoDB commands.
Step 5: Create a Database and Collection
In the mongo shell, let’s create a new database and collection:
use mydb
db.createCollection("users")
db.users.insertOne({name: "John Doe", email: "john@example.com"})
These commands create a database named “mydb”, a collection named “users”, and insert a document into it.
Step 6: Verify Data Persistence
Exit the mongo shell (type exit
), stop the container, and remove it:
docker stop my-mongodb
docker rm my-mongodb
Now, let’s run a new container with a volume to persist our data:
docker run -d --name my-mongodb -p 27017:27017 -v mongodb_data:/data/db mongo
The -v mongodb_data:/data/db
option creates a Docker volume for data persistence.
Connect to this new container and check if your data is still there:
docker exec -it my-mongodb mongo
use mydb
db.users.find()
You should see the document we inserted earlier.
Conclusion:
Running MongoDB in Docker provides a clean, isolated environment that’s easy to set up and tear down. It’s particularly useful for development and testing scenarios where you need to quickly spin up a database instance.
Remember to consider security measures like setting up authentication and using Docker networks for production environments.
So, whether you’re a tech enthusiast, a professional, or just someone who wants to learn more, I invite you to follow me on this journey. Subscribe to my blog and follow me on social media to stay in the loop and never miss a post.
Together, let’s explore the exciting world of technology and all it offers. I can’t wait to connect with you!”
Connect me on Social Media: https://linktr.ee/mdshamsfiroz
Happy learning!
Happy coding with MongoDB and Docker!