• Get In Touch
June 27, 2016

Create A MongoDB Docker Container with Attached Storage Volume

Need Hosting? Try ours, it's fast, reliable and feature loaded with support you can depend on.
View Plans

Docker is an open-source project that automates the deployment of applications inside software containers.

MongoDB is an open-source document database and leading NoSQL database. MongoDB is written in C++.

Features

Docker containers wrap up a piece of software in a complete filesystem that contains everything it needs to run: code, runtime, system tools, system libraries – anything you can install on a server. This guarantees that it will always run the same, regardless of the environment it is running in.

MongoDB is document database in which one collection holds different different documents, which makes it schema less. Number of fields, content and size of the document can be differ from one document to another. It also has deep query-ability. MongoDB supports dynamic queries on documents using a document-based query language that’s nearly as powerful as SQL. MongoDB is easy to scale & conversion / mapping of application objects to database objects is not needed. It uses internal memory for storing the (windowed) working set, enabling faster access of data.

Using Docker and containers for deploying MongoDB instances will bring several benefits, such as:

  • Easy to maintain, highly configurable MongoDB instances.
  • Ready to run and start working within milliseconds.
  • Based on globally accessible and shareable images.

In this tutorial, we will learn how to build a Docker image with MongoDB.

Requirements

  • An operating system which supports Docker containers & has Docker installed.
  • A static IP Address for your server.
  • A non-root user account with sudo privilege set up on your server.

Create a Docker Container

Create a directory in which we will write Dockerfile and keep all configuration files in it, if required.

sudo mkdir /Docker
cd /Docker

Create a file named Dockerfile using the following command,

sudo nano Dockerfile

Add following content into the Dockerfile.

    FROM ubuntu
    MAINTAINER Firstname Lastname your@email.com

    RUN 
       apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0RBB10 && 
       echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list && 
       apt-get update && 
       apt-get install -y mongodb-org

    VOLUME ["/data/db"]
    WORKDIR /data

    EXPOSE 27017

    CMD ["mongod"]

Save and exit the file.

The following is an explanation of what we used to build the Dockerfile.

  • The FROM specifies the Base Image from which we will start building.

  • The MAINTAINER instruction allows you to set the Author field of the generated images.

  • The RUN instruction will execute the setup steps found on the MongoDB site in their correct order.

  • The VOLUME instruction tells the container to mount ‘/data/db’ as attached data volume to container.

  • The WORKDIR instruction sets the working directory for any RUN, CMD, ENTRYPOINT, COPY and ADD instructions that follow it in the Dockerfile.

  • The EXPOSE instructs the container to expose the given port to the host system.

  • The CMD instruction is set to run MongoDB process when container starts.

After creating the Dockerfile, you can build the image by running following command.

sudo docker build -t mongodb

Run docker images command and verify your Docker image is in the list.

sudo docker images

You should see the following output:

    REPOSITORY                  TAG                 IMAGE ID            CREATED             SIZE
    frodenas/mongodb        latest      e17b56e5200a        5 seconds ago   235.3 MB
    firefox-instance            latest              8e61bff07fa0        4 weeks ago         354.6 MB
    centos                      latest              d0e7f81ca65c        4 weeks ago         196.6 MB
    debian                      latest              f50f9524513f        5 weeks ago         125.1 MB
    apache/ubuntu               latest              196655130bc9        5 weeks ago         224.1 MB
    apache-instance             latest              7da78270c5f7        5 weeks ago         224.1 MB

Next, start the docker container by running the following command:

docker run --name mongo-dev -d -v /opt/mongodb:/data/db -p 27017:27017 mongodb

  • The -v switch indicates your our mapping your local host /opt/mongodb directory with the /data/db directory within the container.
  • The –name switch names the running container.
  • The -p switch maps the port of MongoDB process running inside a container.
  • The -d switch starts the docker container as daemon or in background.

Run docker ps to check the container status. We have mapped MongoDB port 27017 of container to local host’s port 27017 while starting container.

To verify MongoDB, Let’s try to connect to the server and create a new db with a record. We will need the mongo client tools installed to issue the next commands.

Run following command to connect to MongoDB server running inside Docker container,

mongo localhost:27017

You should get a Mongo prompt after running above command.

Create new database,

use mynewdb

Now let’s use MongoDB’s sample data script to populate a testData collection,

    for (var i = 1; i <= 15; i++) {
       db.testData.insert( { x : i } )
    }

Now, query the data,

db.testData.find()

To exit the MongoDB shell,

quit()

Now, let's check that the instance of MongoDB container has db files outside of the container by running ls on /opt/mongodb. You should see similar output shown below.

journal local.0 local.ns mongod.lock _tmp mynewdb.0 mynewdb.ns

Now check what happens when the container is restarted?

sudo docker restart mongo-dev

Now try to re-connect to MongoDB and validate the data exists.

Conclusion

In this tutorial we learned to create a MongoDB Docker container and store the data in a volume which stores the persistent data across container restart.

Need Hosting? Try ours, it's fast, reliable and feature loaded with support you can depend on.
View Plans

Share this Article!

Related Posts

Node.js Authentication – A Complete Guide with Passport and JWT

Node.js Authentication – A Complete Guide with Passport and JWT

Truth be told, it’s difficult for a web application that doesn’t have some kind of identification, even if you don’t see it as a security measure in and of itself. The Internet is a kind of lawless land, and even on free services like Google’s, authentication ensures that abuses will be avoided or at least […]

Node.js and MongoDB: How to Connect MongoDB With Node

Node.js and MongoDB: How to Connect MongoDB With Node

MongoDB is a document-oriented NoSQL database, which was born in 2007 in California as a service to be used within a larger project, but which soon became an independent and open-source product. It stores documents in JSON, a format based on JavaScript and simpler than XML, but still with good expressiveness. It is the dominant […]

Using MySQL with Node.js: A Complete Tutorial

Using MySQL with Node.js: A Complete Tutorial

Although data persistence is almost always a fundamental element of applications, Node.js has no native integration with databases. Everything is delegated to third-party libraries to be included manually, in addition to the standard APIs. Although MongoDB and other non-relational databases are the most common choice with Node because if you need to scale an application, […]

Node.Js Vs Django: Which Is the Best for Your Project

Node.Js Vs Django: Which Is the Best for Your Project

Django and NodeJs are two powerful technologies for web development, both have great functionality, versatile applications, and a great user interface. Both are open source and can be used for free. But which one fits your project best? NodeJs is based on JavaScript, while Django is written in Python. These are two equally popular technologies […]

Nodejs Vs PHP:  Which Works Best?

Nodejs Vs PHP: Which Works Best?

Before getting into the “battle” between Node.js and PHP we need to understand why the issue is still ongoing. It all started with the increased demand for smartphone applications, their success forcing developers to adapt to new back-end technologies that could handle a multitude of simultaneous requests. JavaScript has always been identified as a client-side […]