How to Install MongoDB Inside Docker Container

Cloud Native is a term created by the devops community to describe the ecosystem to run containers in a distributed environment.  In this tutorial we will install MongoDB inside a docker container that can be used in a Cloud Native environment.

Installing MongoDB

Run the container with local mount connected your folder. Note that you have to have an absolute path to the directory, we get around this by using the “print working directory” command.

docker run --name mongo-db-container -v "$PWD"/env/mongodb/data:/data/db -d mongo

The ‘-v’ flag mounts the mongo db storage files to our current working directory by using $PWD to “print working directory”. We can see this works by using the ‘tree’ command:

$ tree
.
└── env
 └── mongodb
 └── data
 ├── WiredTiger
 ├── WiredTiger.lock
 ├── WiredTiger.turtle
 ├── WiredTiger.wt
 ├── WiredTigerLAS.wt
 ├── _mdb_catalog.wt
 ├── collection-0-6771647859522219463.wt
 ├── collection-2-6771647859522219463.wt
 ├── diagnostic.data
 │   ├── metrics.2017-01-23T18-22-51Z-00000
 │   └── metrics.interim
 ├── index-1-6771647859522219463.wt
 ├── index-3-6771647859522219463.wt
 ├── index-4-6771647859522219463.wt
 ├── journal
 │   ├── WiredTigerLog.0000000001
 │   ├── WiredTigerPreplog.0000000001
 │   └── WiredTigerPreplog.0000000002
 ├── mongod.lock
 ├── sizeStorer.wt
 └── storage.bson

5 directories, 19 files

Log into the mongo-db-container container shell:

docker exec -it mongo-db-container /bin/bash

Verify that Mongo installed in the container:

mongo --version

This should display an output like this:

# mongo --version
MongoDB shell version v3.4.1
git version: 5e103c4f5583e2566a45d740225dc250baacfbd7
OpenSSL version: OpenSSL 1.0.1t 3 May 2016
allocator: tcmalloc
modules: none
build environment:
 distmod: debian81
 distarch: x86_64
 target_arch: x86_64

Congratulations! You now have Mongodb installed inside Docker!

Helpful MongoDB commands

Log into mongo shell:

mongo

List databases:

show dbs

Use a database:

use mongo-db-container

(If one doesn’t exist with the same name, one will be created after a collection is inserted)

Insert collection:

db.users.insert({username: "Bigbassroller", password: "secret-pw"})

List collections

show collections

List all entries inside a collection:

db.users.find()

Update recorded entry:

db.users.update({username:"Bigbassroller"},{$set:{password:"new-secret-pw"}})

Links: