Home MongoDB Install MongoDB Using Vagrant In Linux

Install MongoDB Using Vagrant In Linux

By Karthick
469 Views

Vagrant is an open source software that provides a clean, easy to configure, reproducible, and portable development environment. Using Vagrant, we can easily and quickly build and maintain different virtual software development environments. In this guide, we will see how to install mongoDB using Vagrant in Linux operating system.

What is mongoDB?

MongoDB is a NoSQL document-oriented database used when you have to handle humongous data. MongoDB uses collections and documents to store the data. Documents are a set of key-value pairs (JSON) stored in collections.

Below is a sample document in JSON format for your reference.

{
   title: 'Install MongoDB-5 In Linux Using Vagrant',
   url: 'https://ostechnix.com/',
   Site: 'ostechnix',
   owner: 'sk',
   author: 'Karthick',
   tags: ['community Edition', 'Linux', 'NoSQL', 'MongoDB5'],
   mongo_version: 5
}

The most recent version of mongoDB is 5. MongoDB is available in two variants - community edition and enterprise edition. In this article, we will Install the mongoDB 5 community edition using Vagrant in Linux.

Prerequisites

Before proceeding to the next steps, make sure you have installed Oracle VirtualBox and Vagrant in your Linux machine. Oracle VirtualBox is available in the official repositories of popular Linux distributions, so you can install it using using your distribution's default package manager.

And then, install Vagrant on your Linux system as described in the following link.

Initialize Vagrant environment

For the purpose of this guide, I will be using Oracle Virtualbox as the hypervisor, which is the default provider for Vagrant. And I am using Ubuntu 20.04 Vagrant box to deploy mongoDB in it.

Create a new project directory for MongoB.

$ mkdir mongodb_vagrant

Switch to the project directory and initialize the vagrant environment by running the following command:

$ cd mongodb_vagrant
$ vagrant init -m "ubuntu\focal64"

This will create a new Vagrantfile in the project directory. Open the Vagrantfile in your favorite editor and copy/paste the following lines in it:

# -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant.configure("2") do |config|
  config.vm.box = "ubuntu/focal64"
  config.vm.box_check_update = false
  config.vm.define "MongoDB5"
  config.vm.network "public_network"
  config.vm.provision "shell", path: "mongo-bootstrap.sh"
  config.vm.provider "virtualbox" do |v|
    v.memory = 2048
    v.cpus = 2
    v.name = "MongoDB-5"
  end
end

Allow me to explain the important parameters in the above code.

The parameter vm.box points to the underlying Linux distribution that we use to install MongoDB. In our case, it is Ubuntu 20.04 LTS.

config.vm.box = "ubuntu/focal64"

Every time when you boot up the VM, Vagrant will check if there is any update for the box that is used. Setting the parameter box_check_update = false will disable update check. This is optional! You prefer to update Vagrant box, you can remove this line:

config.vm.box_check_update = false

Every vagrant VM is assigned with default as the name. The parameter vm.define can be used to set a custom name to your VM. In this case, I have set the name to MongoDB5.

config.vm.define "MongoDB5"

You can run the global-status command to check the name assigned to the VM:

$ vagrant global-status --prune

id       name        provider   state    directory
--------------------------------------------------------------------------------------------

76c3e81  MongoDB5    virtualbox running  /home/karthick/Work/Lab/vagrant/mongodb_vagrant

The following parameter decides how the networking will be set up for your VM.

config.vm.network "public_network"

I have set up Public_network. I also have not provided the interface name since it may vary and the interface to be connected will be prompted during vagrant up as shown in the below log output.

==> MongoDB5: Available bridged network interfaces:
1) wlo1
2) eno1
3) docker0
==> MongoDB5: When choosing an interface, it is usually the one that is
==> MongoDB5: being used to connect to the internet.
==> MongoDB5: 
    MongoDB5: Which interface should the network bridge to? 1
==> MongoDB5: Preparing network interfaces based on configuration...
    MongoDB5: Adapter 1: nat
    MongoDB5: Adapter 2: bridged
==> MongoDB5: Forwarding ports...
    MongoDB5: 22 (guest) => 2222 (host) (adapter 1)

I have used shell provisioner to install and set up MongoDB. The script name is mongo-bootstrap.sh. You can name the script as you wish.

config.vm.provision "shell", path: "mongo-bootstrap.sh"

The following parameters will configure the memory and CPU for your virtual machine. I have set the memory to 2gigs and 2 Vcores. You can increase and decrease the values by modifying the v.memory and v.cpus parameters.

config.vm.provider "virtualbox" do |v|
    v.memory = 2048
    v.cpus = 2
    v.name = "MongoDB-5"
  end

The name assigned to the parameter v.name is what will be displayed in your Virtualbox GUI.

VBox Name
VBox Name

Create bootstrap shell script

As I stated earlier, a shell provisioner is used for installing and configuring the mongoDB in the vagrant box.

Create a file named mongo-bootstrap.sh:

$ vi mongo-bootstrap.sh

And add the following piece of code in it:

#!/usr/bin/env bash

# Adding Repo
echo "-------------------------- ADDING REPO -------------------------------------"
wget -qO - https://www.mongodb.org/static/pgp/server-5.0.asc | sudo apt-key add -
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/5.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-5.0.list

# Updating Package Index and Installing MongoDB-5
echo "-------------------------- UPDATING PACKAGE INDEX -------------------------------------"
sudo apt update

echo "-------------------------- INSTALL PACKAGES --------------------------"
sudo apt install -y mongodb-org net-tools

# Start and Enable Mongod 
echo "-------------------------- START & ENABLE MONGOD --------------------------"
sudo systemctl enable --now mongod

sleep 20

# Create user
echo "-------------------------- CREATE VAGRANT USER --------------------------"
mongosh << BLK
use admin
db.createUser(
{
    user: "vagrant",
    pwd: "vagrant",
    roles: [
              { role: "userAdminAnyDatabase", db: "admin" },
              { role: "readWriteAnyDatabase", db: "admin" },
              { role: "dbAdminAnyDatabase", db: "admin" },
              { role: "clusterAdmin", db: "admin" }
           ]
})
exit
BLK


## Enable Authorization

sudo cat << EOB >> /etc/mongod.conf
#security:
security:
    authorization: "enabled"
EOB

echo "-------------------------- RESTARTED MONGOD --------------------------"
sudo systemctl restart mongod

Press ESC and type :wq to save the file and close it.

Let me give you a brief description of each section in the above code.

By default, there is an older version of mongoDB that ships with Ubuntu. If you want mongodDB latest version, you have to add the official repository in the mongo-bootstrap.sh file.

The following section of code will take care of adding the repository, updating the package Index, installing mongoDB, and bring up the mongod daemon.

Add mongodb official repository
Add mongodb official repository

The following block of code will create a vagrant user with admin privileges. The username will be vagrant and the password is also set to vagrant. You can set a different username and password if you wish.

Create Vagrant user
Create Vagrant user

By default, there is no security policy enforced. Any user can invoke mongosh shell and start using the database. To enforce role-based access control the following parameter should be added to /etc/mongod.conf file.

This chunk of code will take care of adding the parameter and restart the mongod daemon for changes to be effective.

Enable Authorization
Enable Authorization

Heads Up: Before enabling RBAC (Role based access control), an admin user should be created, so he/she can grant access to other users in any database.

Start mongoDB Vagrant machine

Once the Vagrant file and bootstrap script are created, you can start the VM by running the following command:

$ vagrant up

Now, wait until the machine is booted up and the mongoDB installation and configuration part is taken care of by the bootstrap script. This will take a couple minutes.

To login to the VM, run the following command:

$ vagrant ssh

MongoDB listens at port 27017. You can use the netstat command to check if the port is in listening status.

$ sudo netstat -tlnup

Sample output:

Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
tcp        0      0 127.0.0.1:27017         0.0.0.0:*               LISTEN      3306/mongod

Run the following command to check the status of the mongod service:

$ systemctl status mongod

Sample output:

● mongod.service - MongoDB Database Server
     Loaded: loaded (/lib/systemd/system/mongod.service; enabled; vendor preset: enabled)
     Active: active (running) since Tue 2021-08-17 10:24:36 UTC; 2h 21min ago
       Docs: https://docs.mongodb.org/manual
   Main PID: 3306 (mongod)
     Memory: 162.3M
     CGroup: /system.slice/mongod.service
             └─3306 /usr/bin/mongod --config /etc/mongod.conf

Access mongoDB shell

The mongo shell is a cli client to connect to mongoDB. Now it is replaced with a new cli client mongosh from mongoDB V5. 

Run mongosh in the terminal to start using the shell. Since RBAC is enabled you have to provide the credentials.

You can connect to the MongoDB database using monosh using the following connection string.

$ mongosh mongodb://<username>:<password>@localhost:<port>/<database>

Here I am connecting with a newly created vagrant user.

$ mongosh mongodb://vagrant:[email protected]:27017/admin

Alternatively, you can start the shell and run the following commands to connect:

$ monosh
$ use admin
$ db.auth("username","password")
$ db.auth("vagrant","vagrant")
Connect to the MongoDB database as Vagrant user
Connect to the MongoDB database as Vagrant user

Manage mongoDB vagrant box from command line

The following vagrant commands will help you to manage the mongoDB VM via CLI:

$ vagrant --global-status --prune      # check the status of the machine 
$ vagrant halt                         # Stop the VM
$ vagrant destroy                      # Destroy the VM and associated VM disk.
$ vagrant ssh                          # Login to Remote Host

For more detailed Vagrant commands usage, refer our Vagrant tutorial:

Conclusion

In this step by step guide, we have seen how to easily set up mongoDB in Ubuntu 20.04 Vagrant box. If you're testing a mongoDB project or learning mongoDB, you can quickly spin up a Vagrant box and install mongodDB in the Vagrant box as described here.

You May Also Like

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More