Introduction to Running MongoDB 6 with Docker

Introduction to Running MongoDB 6 with Docker
Photo by Rubaitul Azad / Unsplash

In this article we explore using MongoDB with Docker. MongoDB is a schemaless database, meaning that arbitrary json documents are stored instead of using some sort of structured table format. Using MongoDB  is a fast way to prototype new ideas without needing to do a lot of database setup, including database creation, table creation and maintaining table schemas. With the appropriate permissions, MongoDB allows for creation of database and collections on the fly for data storage – where as traditional database systems require database and table setup before hand.

In this guide, a development instance of MongoDb will be launched using docker and launch a slightly hardened version with an admin user and authentication enabled.

We'll be using a docker image provided from dockerhub, with the current version of MongoDB 6. There are some challenges with using MongoDB 6 on the latest version of Ubuntu 22.04, as libssl1.1 is not available by default and there could be other issues when installing on other OS's. Going the docker route can make using the latest version of MongoDB easier without worrying about the specifics of the installation environment.

Prerequisites for this tutorial

You will need the following installed in your environment:

  • Docker
  • Git (optional)

MongoDB Quickstart

The steps below will get MongoDB running just using the docker run command

  1. Start MongoDB with docker with docker run -d --name my-mongo -p 27017:27017 mongo:6. The -d flag runs the container in detached mode, meaning it will run in the background. The --name flag allows you to specify a name for the container, in this case "my-mongo". The -p flag will expose port 27017 from inside the container to the same port on our computer.
  2. See that the docker container is running using docker ps
  3. Start a mongo shell using mongosh from the terminal inside of the container
  4. Insert sample data inside of the default test collection using db.test.insert({x:1})
  5. Show that you are able to fetch the data from the collection using db.test.find({}) -- this filter selects for all documents inside of the collection
  6. You can exit from the mongo shell using ctrl-d
  7. Once you are done with the quick start container, it can be shutdown with docker stop my-mongo and the stopped container can be deleted with docker container rm my-mongo
Running a MongoDB container using only Docker commands

Limitations of using the MongoDB Quickstart method

Using the quickstart method of starting a MongoDB database is fine for quick testing, however there are some limitations when using this method or testing:

  1. Data persistence: By default, data stored in a Docker container is not persisted when the container is stopped or removed. This means that if you stop or remove the MongoDB container, any data stored in the container will be lost. To persist data, you can mount a volume to the container, which allows you to store data on the host machine instead of inside the container.

  2. Authentication: By default, MongoDB allows anyone to connect to the database without authentication. This can be a security risk, as anyone with access to the database can read, write, and delete data. To secure the database, you should enable authentication and a user with appropriate permissions should be created.

A Persistent Docker Setup for MongoDB

Now that we've shown a simple test setup of the database is possible, the next step will be to create a setup so that data is stored persistently and with authentication is enabled for security.

In this example, we'll use a docker-compose file to define the setup and use simple docker compose up and docker compose down commands to manage the container.

A Sample docker-compose.yml file

version: "3.8"
services:
  mongo:
    image: mongo:6
    ports:
      - 27017:27017
    volumes:
      - type: bind
        source: ./mongo.yml
        target: /etc/mongod.conf
      - type: volume
        source: mongo_volume
        target: /data/db
    environment:
      MONGO_INITDB_ROOT_USERNAME: admin
      MONGO_INITDB_ROOT_PASSWORD: test
    command: --config /etc/mongod.conf

volumes:
  mongo_volume:
A sample docker compose file to start a docker container with a single root user

The above docker compose file uses a Mongo 6 image to run as a container with port 27017 exposed and with a docker volume mounted at /data/db. A root user is defined (for testing purposes here) using the environment variables MONGO_INITDB_ROOT_USERNAME and MONGO_INITDB_ROOT_PASSWORD; I suggest that more secure usernames and passwords are used as this is for demonstration purposes. Finally, a local file mongo.yml is defined and mounted at /etc/mongo.conf which provides configuration settings when the database is started (note that the mongo.conf file is simply a yaml file with a different file extension).

The details of the mongo.yml file is provided below:

net:
  bindIpAll: true
  port: 27017
security:
  authorization: enabled
storage:
  dbPath: /data/db

The configuration above tells the running MongoDB server to bind to be available to all network interfaces at port 27017 when running inside of the docker container, enables authentication and sets the path to store database files at /data/db within the container. If you wish to make more modifications to the file, detailed information about the available options are available at the MongoDB documentation page, here.

A Short Note about MongoDB Authentication

MongoDB provides other methods of authentication to the database, including x.509, Kerberos and LDAP. Topics to configure these methods of authentication is beyond the scope of this tutorial but maybe useful depending on your infrastructure setup. Details about other authentication methods are provided on MongoDB's authentication documentation page.

A Short Note about using a Docker Volume for Persistent Storage

If you expect to store large amounts of data it might be advantageous to ensure that your MongoDB data is stored on a disk with sufficient space. By default, docker stores volumes on unix machines at /var/lib/docker/volumes/. Several options are available to move this location around:

  1. The first option would be to create a symbolic link to a drive that has ample space to handle the expected space to be used by MongoDB
  2. The second option would be to configure docker to use a path on a drive with sufficient space for all docker volumes by changing the --data-root setting. This setting can be change at invocation or by creating a configuration file with the appropriate setting.

Using our tutorial repository from github

A repository for this setup is provided in our mongodb-docker-tutorial in Github. The code to run the docker container can be cloned with git clone https://github.com/spherex-dev/mongodb-docker-tutorial.git and running docker compose up -d will start the MongoDB container with the predefined settings provided via the docker-compose.yml and mongo.yml files.

The username and password for this example is admin for both and authentication is done via docker exec -it mongodb-docker-tutorial-mongo-1 -u admin -p admin testing to verify that authenticating with an incorrect password can be done by replacing the password with any random string.

The screen cast below illustrates running starting MongoDB via docker compose:

Summary

By following the above steps you should be able to run your own docker based MongoDB instance that you're able to connect to using a docker volume for persistent storage. We discuss how to enable authentication with the creation of a root user using the environment variables provided in a docker-compose.yml file.