Jump toUpdate content
Installing and Securing MongoDB on Ubuntu 16.04
- database
- compute
- mysql
- mongoDB
- UFW
- bindIP
MongoDB is a document-oriented database that is free and open-source. It considered one of the most popular NoSQL database engines because it is scalable, powerful, reliable and easy to use. In contrast to relational database, MongoDB does not require a deep predefined schema before you can add data since it can be altered at any time. As it uses the NoSQL concept, data rows are stored in JSON-like documents which allows arbitrary data to be inserted.
- You have an account and are logged into the Scaleway console
- You have configured your SSH Key
- You have created an Instance that runs Ubuntu 16.04
- You have sudo privileges or access to the root user.
Setting up MongoDB
Adding MongoDB Repository
You should always use the official MongoDB mongodb-org
packages, which are kept up-to-date with the most recent major and minor MongoDB releases.
Connect to your instance via SSH.
ssh root@your.instance.ip.address
If you do not know your server IP, you can list your existing servers using
scw ps
(Scaleway CLI). Typeyes
ory
when prompted to confirm that we wish to proceed. If the Scaleway CLI is not installed, you have several options:- (Preferred) On Mac OS using Homebrew and launching
brew install scw
- On Mac OS using a manual install
Install the latest stable release on Mac OS X manually:
# prepare for first install and upgrade
mkdir -p /usr/local/bin
mv /usr/local/bin/scw /tmp/scw.old
# get latest release
wget "https://github.com/scaleway/scaleway-cli/releases/download/v1.19/scw-darwin-amd64" -O /usr/local/bin/scw
# test
scw version
Install the latest release on Linux:
# get latest release
export ARCH=amd64 # can be 'i386', 'amd64' or 'armhf'
wget "https://github.com/scaleway/scaleway-cli/releases/download/v1.19/scw_1.19_${ARCH}.deb" -O /tmp/scw.deb
dpkg -i /tmp/scw.deb && rm -f /tmp/scw.deb
# test
scw version- On Windows by downloading the .exe
Important:If you use the root user, you can remove the
sudo
before each command.- (Preferred) On Mac OS using Homebrew and launching
Update Ubuntu package manager
sudo apt-get update
Upgrade the Ubuntu packages already installed
sudo apt-get upgrade
Import the key for the official MongoDB repository (Ubuntu ensures the authenticity of software packages by verifying that they are signed with GPG keys.)
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 0C49F3730359A14518585931BC711F9BA15703C6
Executing: /tmp/tmp.68PpBponrV/gpg.1.sh --keyserver
hkp://keyserver.ubuntu.com:80
--recv
0C49F3730359A14518585931BC711F9BA15703C6
gpg: requesting key A15703C6 from hkp server keyserver.ubuntu.com
gpg: key A15703C6: public key "MongoDB 3.4 Release Signing Key <packaging@mongodb.com>" imported
gpg: Total number processed: 1
gpg: imported: 1 (RSA: 1)Add the MongoDB repository details so that Ubuntu’s
apt
command-line tool will know where to download the packages. Execute the following command to create a list file for MongoDB.echo "deb [ arch=amd64,arm64 ] http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.4.list
Update the packages list
sudo apt-get update && sudo apt-get upgrade -y
Installing MongoDB
Install the
mongodb-org
meta-package, which includes the daemon, configuration and init scripts, shell, and management tools on the server.sudo apt-get install mongodb-org
Press enter or type
Y
to proceed when prompted. Once the installation is completed, we start the MongoDB daemonsudo systemctl start mongod
Since
systemctl
does not provide output, verify that the service has started properly.sudo systemctl status mongod
mongod.service - High-performance, schema-free document-oriented database
Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset:
Active: active (running) since Wed 2018-xx-yy 13:04:39 UTC; 1min 52s ago
Docs: https://docs.mongodb.org/manual
Main PID: 25081 (mongod)
CGroup: /system.slice/mongod.service
└─25081 /usr/bin/mongod --config /etc/mongod.confPress
q
to exit.Ensure that it restarts automatically at each boot
sudo systemctl enable mongod
Created symlink from /etc/systemd/system/multi-user.target.wants/mongod.service to /lib/systemd/system/mongod.service.
Securing MongoDB
The default installation of MongoDB is vulnerable because no authentication is required to interact with the database. Any user could create and destroy databases, as well as read from and write to their contents by default. To secure MongoDB, we need to create an administrative user and enable authentication.
Connect to the Mongo shell to add a new user
mongo
MongoDB shell version v3.4.15
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.15
Server has startup warnings:
2018-06-27T13:04:39.592+0000 I STORAGE [initandlisten]
2018-06-27T13:04:39.592+0000 I STORAGE [initandlisten] ** WARNING: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine
2018-06-27T13:04:39.592+0000 I STORAGE [initandlisten] ** See http://dochub.mongodb.org/core/prodnotes-filesystem
2018-06-27T13:04:39.706+0000 I CONTROL [initandlisten]
2018-06-27T13:04:39.706+0000 I CONTROL [initandlisten] ** WARNING: Access control is not enabled for the database.
2018-06-27T13:04:39.706+0000 I CONTROL [initandlisten] ** Read and write access to data and configuration is unrestricted.
2018-06-27T13:04:39.706+0000 I CONTROL [initandlisten]
2018-06-27T13:04:39.706+0000 I CONTROL [initandlisten]
2018-06-27T13:04:39.706+0000 I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag is 'always'.
2018-06-27T13:04:39.706+0000 I CONTROL [initandlisten] ** We suggest setting it to 'never'
2018-06-27T13:04:39.706+0000 I CONTROL [initandlisten]You can choose any preferred name for the administrative user since the privilege level is assigned from the role of
userAdminAnyDatabase
.The
admin
database designates where the credentials are stored. You can learn more about authentication in the MongoDB Security Authentication section.Set the username of your choice and be sure to pick your own secure password and substitute them in the command below:
use admin
db.createUser(
{
user: "AdminOce",
pwd: "PWD2018AdminOce",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)use admin
switched to db admin
> db.createUser(
... {
... user: "AdminOce",
... pwd: "PWD2018AdminOce",
... roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
... }
... )
Successfully added user: {
"user" : "AdminOce",
"roles" : [
{
"role" : "userAdminAnyDatabase",
"db" : "admin"
}
]
}Type
exit
and press ENTER or useCTRL+C
to leave the client.> exit
bye
Enabling authentication
In order to enforce authentication, we need to enable authentication and restart the MongoDB daemon.
Open the configuration file
sudo nano /etc/mongod.conf
In the
#security
section, remove the hash in front of security to enable the section. Then, we add the authorization lines (indented with two spaces) as per the following excerpt below:security:
authorization: "enabled"Restart the daemon
sudo systemctl restart mongod
Check the status to verify that the service has rebooted
sudo systemctl status mongod
mongod.service - High-performance, schema-free document-oriented database
Loaded: loaded (/lib/systemd/system/mongod.service; enabled; vendor preset: e
Active: active (running) since Wed 2018-xx-yy 15:36:34 UTC; 2min 16s ago
Docs: https://docs.mongodb.org/manual
Main PID: 25593 (mongod)
CGroup: /system.slice/mongod.service
└─25593 /usr/bin/mongod --config /etc/mongod.confPress
q
to exit.Ensure that the daemon restarts automatically at boot
sudo systemctl enable mongod
If we see Active:
active (running)
in the output and it ends with something similar to the text below, the restart command was successful:Jun 27 15:36:34 mongoDB systemd[1]: Started High-performance, schema-free document-oriented database.
Testing authentication
Connect without credentials to verify that our actions are restricted
mongo
MongoDB shell version v3.4.15
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.15We are connected to the test database.
Test that the access is restricted with the
show dbs
command:show dbs
2018-06-27T15:55:36.481+0000 E QUERY [thread1] Error: listDatabases failed:{
"ok" : 0,
"errmsg" : "not authorized on admin to execute command { listDatabases: 1.0 }",
"code" : 13,
"codeName" : "Unauthorized"
} :Exit the shell to proceed
> exit
bye
Verifying the administrative user’s access
Connect as our administrator with the
-u
option to supply a username and-p
to be prompted for a password. Supply the database where we stored the user’s authentication credentials with the--authenticationDatabase
option.mongo -u AdminOce -p --authenticationDatabase admin
Once the correct password is entered, we are dropped into the shell, where we can issue the
show dbs
command:MongoDB shell version v3.4.15
Enter password:
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.15
> show dbs
admin 0.000GB
local 0.000GB
Type exit
or press CTRL+C
to exit.
Configuring remote access (Optional)
Enabling UFW
Uncomplicated Firewall (UFW), is a front-end to iptables. Its main goal is to make managing your firewall drop-dead simple and to provide an easy-to-use interface.
Install UFW.
sudo apt-get install ufw
Check UFW status.
sudo ufw status
Enable UFW, as it is probably inactive.
sudo ufw enable
Ensure to allow SSH.
sudo ufw allow OpenSSH
Rerun the UFW status command.
sudo ufw status
Status: active
To Action From
-- ------ ----
OpenSSH ALLOW Anywhere
OpenSSH (v6) ALLOW Anywhere (v6)Allow access to the default MongoDB port
27017
but restrict that access to a specific host.sudo ufw allow from client_ip_address to any port 27017
Re-run this command using the IP address for each additional client that needs access. To double-check the rule, run
ufw status
again:sudo ufw status
To Action From
-- ------ ----
OpenSSH ALLOW Anywhere
27017 ALLOW client_ip_address
OpenSSH (v6) ALLOW Anywhere (v6)
Configuring a public bindIP
To allow remote connections, add our host’s publically-routable IP address to the
mongod.conf
file.sudo nano /etc/mongod.conf
In the
net
section, add the MongoHost’s IP to the bindIp lineNote:Verify your private IP with the
ifconfig
command.net:
port: 27017
bindIp: 127.0.0.1,IP_of_MongoHostRestart the daemon
systemctl restart mongod
Check the daemon status
systemctl status mongod
Active: active (running) since Thu 2018-xx-yy 13:15:35 UTC; 5s ago
Testing remote connections
Ensure that Mongo is listening on its public interface by adding the --host
flag with the IP address from the mongodb.conf file
.
mongo -u AdminOce -p --authenticationDatabase admin --host IP_address_of_MongoHost
MongoDB shell version v3.4.15
Enter password:
connecting to: mongodb://10.15.124.17:27017/
MongoDB server version: 3.4.15
Uninstalling MongoDB
This process will completely remove MongoDB, its configuration, and all databases. This process is not reversible, so ensure that all of your configuration and data is backed up before proceeding.
Stop MongoDB.
sudo service mongod stop
Remove any MongoDB packages that you had previously installed.
sudo apt-get purge mongodb-org*
Remove MongoDB databases and log files.
sudo rm -r /var/log/mongodb
sudo rm -r /var/lib/mongodb