Skip to main content

How to Install MongoDB on Debian 9 and enable remort access and authentication


MongoDB is a free and open-source NoSQL document database with the scalability and flexibility with the querying and indexing. This post will assist you with the installation process of MongoDB, manage its service, enable remote access and securing MongoDB.

Note: Platform Support
MongoDB only provides packages for 64-bit builds of Debian 8 and 9. See Supported Platforms for more information.The mongodb-org
package is officially maintained and supported by MongoDB Inc. and kept up-to-date with the most recent MongoDB releases. This installation procedure uses the mongodb-org package a.k.a the official MongoDB repo.

Step 1 — Installing MongoD

make sure the curl command is installed so that we can use it to add the MongoDB signing key
if you don't have curl installed, install it by running the following command:-


apt install curl

Import the public key used by the package management system.
curl https://www.mongodb.org/static/pgp/server-4.0.asc | apt-key add - 
Create the list file using the command appropriate for your Debian 9 (stretch):

echo "deb http://repo.mongodb.org/apt/debian stretch/mongodb-org/4.0 main" | tee /etc/apt/sources.list.d/mongodb-org-4.0.list

reload the local package database:

apt update

To install the latest stable version, issue the following

apt-get install -y mongodb-org

Enable and start the mongod service to get your MongoDB database running:

systemctl enable mongod

systemctl start mongod

The installation is done, we have started the latest stable version of MongoDB, along with helpful management tools for the MongoDB server. The MongoDB server should be up and running.


Step 2 — Checking the Service and Database


check the service's status

systemctl status mongod
● mongod.service - MongoDB Database Server
Loaded: loaded (/lib/systemd/system/mongod.service; enabled; vendor preset: enabled)
Active: active (running) since Fri 2019-05-31 08:05:37 EDT; 4min 25s ago
Docs: https://docs.mongodb.org/manual
Main PID: 1255 (mongod)
Tasks: 27
CGroup: /system.slice/mongod.service
└─1255 /usr/bin/mongod --config /etc/mongod.conf

May 31 08:05:37 www systemd[1]: Started MongoDB Database Server.



According to systemd,out put above the MongoDB server is up and running
So we can actual connecting to the database server and executing a diagnostic command

 mongo --eval 'db.runCommand({ connectionStatus: 1 })'

MongoDB shell version v4.0.10 
connecting to: mongodb://127.0.0.1:27017/?gssapiServiceName=mongodb --- server address & port
Implicit session: session { "id" : UUID("69cd3d0a-a694-4af3-ad3b-837da00403de") }
MongoDB server version: 4.0.10  ----------- current database version
{
        "authInfo" : {
                "authenticatedUsers" : [ ],
                "authenticatedUserRoles" : [ ]
        },
        "ok" : 1 -----  output of the status command
}


Step 3 — Managing the MongoDB Service

MongoDB is installed as a systemd service, which means that we can manage it using standard systemd commands alongside all other system services in Debian. 

systemctl status mongod ------- verify the status of the service

systemctl stop mongod --------- stop the server anytime

systemctl start mongod ---------- Start the server

systemctl restart mongod ------ restart the server

systemctl disable mongod --------- disable the automatic startup

systemctl enable mongod ---------- enable the automatic starup

Step 4 — Enable the MongoDB Remote Access

MongoDB is currently only listening on the local address 127.0.0.1. To allow remote connections, add your server's publicly-routable IP address to the mongod.conf file.

 nano /etc/mongod.conf

# network interfaces
net:
  port: 27017
  bindIp: 127.0.0.1, 192.168.0.247 -------  #Add your server's IP address


 After saving the file restart MongoDB

systemctl restart mongod


Step 5 — Adding an Administrative User

Authentication is disabled by default, so any users on the local system have complete access to the databases. To secure this we'll create an administrative user, enable authentication and test.
In oder to add our user, we'll connect to the Mongo shell, run the following command to connect to the shell.

mongo

The output below when we use the Mongo shell warns us that access control is not enabled for the database and that read/write access to data and configuration is unrestricted.


MongoDB shell version v4.0.10
connecting to: mongodb://127.0.0.1:27017/?gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("7025a1d8-c45a-48b2-8c9d-dde5327b7d9b") }
MongoDB server version: 4.0.10
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
        http://docs.mongodb.org/
Questions? Try the support group
        http://groups.google.com/group/mongodb-user
Server has startup warnings:
2019-05-31T08:48:40.151-0400 I STORAGE  [initandlisten]
2019-05-31T08:48:40.151-0400 I STORAGE  [initandlisten] ** WARNING: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine
2019-05-31T08:48:40.151-0400 I STORAGE  [initandlisten] **          See http://dochub.mongodb.org/core/prodnotes-filesystem
2019-05-31T08:48:43.812-0400 I CONTROL  [initandlisten]
2019-05-31T08:48:43.812-0400 I CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2019-05-31T08:48:43.812-0400 I CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2019-05-31T08:48:43.812-0400 I CONTROL  [initandlisten]
---
Enable MongoDB's free cloud-based monitoring service, which will then receive and display
metrics about your deployment (disk utilization, CPU, operation statistics, etc).

The monitoring data will be available on a MongoDB website with a unique URL accessible to you
and anyone you share the URL with. MongoDB may use this information to make product
improvements and to suggest MongoDB products and deployment options to you.

To enable free monitoring, run the following command: db.enableFreeMonitoring()
To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
---

>

> use admin
switched to db admin
> db.createUser(
... {
... user: "admin",
... pwd: "Password",
... roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
... }
... )
Successfully added user: {
        "user" : "admin",
        "roles" : [
                {
                        "role" : "userAdminAnyDatabase",
                        "db" : "admin"
                }
        ]
}
> exit ---- Type 'exit' and press ENTER or use CTRL+C to leave the client.
bye



What we have archive so far is that our user will be allowed to enter credentials, but they will not be required to do so until we enable authentication and restart the MongoDB daemon.


Step 6 — Enabling Authentication

Authentication is enabled in the mongod.conf file. Once we enable it and restart mongod, users still will be able to connect to Mongo without authenticating, but they will be required to provide a username and password before they can interact. 

open the configuration file:
nano /etc/mongod.conf
 

security: --- In the #security section, remove the hash
  authorization: "enabled"  ---- add the authorization setting

 

Note that the “security” line has no spaces at the beginning, and the “authorization” line must be indented with two spaces

save, exit the file and restart the daemon

systemctl restart mongod

use the status option to be sure that the dameon started

systemctl status mongod
 mongod.service - MongoDB Database Server
   Loaded: loaded (/lib/systemd/system/mongod.service; enabled; vendor preset: enabled)
   Active: active (running) since Fri 2019-05-31 09:42:15 EDT; 5s ago
     Docs: https://docs.mongodb.org/manual
 Main PID: 1499 (mongod)
    Tasks: 3
   CGroup: /system.slice/mongod.service
           └─1499 /usr/bin/mongod --config /etc/mongod.conf

May 31 09:42:15 www systemd[1]: Started MongoDB Database Server.

Having verified the daemon is up, let's test authentication.

Step 7 — Verifying that Unauthenticated Users are Restricted

 Start by connecting without credentials to verify that our actions are restricted:

mongo
Now that we've enabled authentication, no more warnings.
MongoDB shell version v4.0.10
connecting to: mongodb://127.0.0.1:27017/?gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("aa9011e3-5b8c-48f7-9a5c-363cbd23684e") }
MongoDB server version: 4.0.10
> show dbs
------- we are not able to enumerate available databases

Step 8 — Verifying the Administrative User's Access

mongo -u admin -p --authenticationDatabase admin
MongoDB shell version v4.0.10
Enter password:   
connecting to: mongodb://127.0.0.1:27017/?authSource=admin&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("a89fcd55-2d7c-4bec-9292-07aa019820a5") }
MongoDB server version: 4.0.10
> show dbs
admin   0.000GB  --------- We are able to see the available databases
config  0.000GB
local   0.000GB
> exit
bye

Step 9 — Testing the Remote Connection

We'll test Mongo connectivity on its public interface by adding the --host flag with the IP address from the mongodb.conf file.
 mongo -u admin -p --authenticationDatabase admin --host 192.168.0.247
MongoDB shell version v4.0.10
Enter password:
connecting to: mongodb://192.168.0.247:27017/?authSource=admin&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("385e9d77-87ed-4a42-99b7-1f8a72b94074") }
MongoDB server version: 4.0.10
> show dbs
admin   0.000GB   --------- We are able to see the available databases
config  0.000GB
local   0.000GB
> exit
bye
At this point, any transaction between a remote connection and the MongoDB host is unencrypted so the next step, should be to secure those transactions.
You should follow this post here in order to enable role base authentication so that your able to create databases, otherwise you wont be able to do so.

Popular posts from this blog

How To Install the Anaconda Python Distribution on Debian 9 And Running a public notebook server

Anaconda Distribution is an open-source package manager, environment manager and distribution of Python and R programming languages. With a collection of 1,000+ open source packages with free community support. Designed for data science and machine learning workflows, you can use it whether you are on Windows, macOS or Linux. The Anaconda distribution ships with the conda command-line package management utility. You can learn more about Anaconda and conda by reading the official Anaconda Documentation . Jupyter is a browser-based interpreter that allows you to interactively work with Python and R. Anaconda provides Jupyter as well. You can think of Jupyter as a digital notebook that gives you an ability to execute commands, take notes and draw charts.It’s primarily used by Data Scientists. But I find that very useful tool if you are learning Python or R. It’s basically the same as working on a shell but much better. The Jupyter notebook web application is based on a

How to create REST API using Django REST Framework

This post begins with already working project and app's, I found that there some few requirement's that my project needed to handle and the best option for those requirement's was to use the Django's  Rest Framework. The way that I will tackle this task is more specific to the needs of the project rather than a one to one how to..., that being said you can still follow along, the approach that I'm going to use is easy to follow since I'll be providing a lot of information a log the way for better understanding of the why and how.....this code is available on Github , enough with the alerts and on with the show. Note:  If you would want to mimic the exactly settings then you will need to enable user authentication on your project you can follow this link for details .  Start with the DRF (Django Rest Framework) installation pip3 install djangorestframework For our app to use DRF, we'll have to add rest_framework into our settings.py.   nan

django react app setting up the backend

On the previous article I demonstrated how we can use the generic views along with ModelSerializer classes to rapidly develop our REST APIs. Knowledge that you will need  in your career as full stack / backend developer, however think of this article as an extension to the previous one, equipped with what we already know about REST API we will step our game up and discuss about ViewSet, ModelViewset we will dig deep into the concepts of Routers which allow us to manage our api routes in a simple and sophisticated manner as well as helping to speed up building APIs even further. There for on part II of this article i'll work you through on how React application can consume this RESTful API. There for at the end of the day we will have a full stack web app, in short we strat our development at the backend then later on we move at the frontend... so are you excited and ready to take the challange? lets do this then..... you can get source code for the bakend on github Preparat