MongoDB Installation - Linux(CentOs)
Install Mongodb
Manually download and install packages
To install MongoDB database you will need to download rpm package files.You can also download the .rpm files directly from the MongoDB repository. Downloads are organized by Red Hat / CentOS version (e.g. 7), then
MongoDB Packages
mongodb-org-server-4.4.17-1.el7.x86_64.rpm
mongodb-org-shell-4.4.17-1.el7.x86_64.rpm
mongodb-org-mongos-4.4.17-1.el7.x86_64.rpm
mongodb-database-tools-100.2.1.x86_64.rpm
mongodb-org-database-tools-extra-4.4.17-1.el7.x86_64.rpm
SELinux Packages
checkpolicy-2.5.8.el7.x86_64.rpm
polixycoreutils-python-2.5-34.el7.x86_64.rpm
1
Copy all the MongoDB packages to a directory of your choice on your server
sudo cp *.rpm /root/mongodb
install the MongoDB RPM files
sudo yum install -y *.rpm
Use Linux distribution to install packages
Configure the package management system (yum). (source - https://www.mongodb.com/docs/manual/tutorial/install-mongodb-on-red-hat/ )
Create a /etc/yum.repos.d/mongodb-org-4.4.repo file so that you can install MongoDB directly using yum:
[mongodb-org-4.4]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/4.4/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-6.0.asc
Install the MongoDB packages.
To install the latest stable version of MongoDB, issue the following command:
sudo yum install -y mongodb-org
Alternatively, to install a specific release of MongoDB, specify each component package individually and append the version number to the package name, as in the following example:
sudo yum install -y mongodb-org-4.4.17 mongodb-org-database-4.4.17 mongodb-org-server-4.4.17 mongodb-mongosh-4.4.17 mongodb-org-mongos-4.4.17 mongodb-org-tools-4.4.17
You can specify any available version of MongoDB. However yum upgrades the packages when a newer version becomes available. To prevent unintended upgrades, pin the package. To pin a package, add the following exclude directive to your /etc/yum.conf file:
exclude=mongodb-org,mongodb-org-database,mongodb-org-server,mongodb-mongosh,mongodb-org-mongos,mongodb-org-tools
Start MongoDB service
sudo systemctl start mongodb
Verify the status of MongoDB service
sudo systemctl start mongodb
or
sudo netstat -naptu | grep 27017
Configure SELinux
on Centos7 the current SELinux Policy does not allow MongoDB process to access /sys/fs/cgroup which requires to determine the available memory on the system. update the SELinux policy with the following steps
sudo yum install checkpolicy-2.5.8.el7.x86_64.rpm
sudo polixycoreutils-python-2.5-34.el7.x86_64.rpm
Create an SELinux policy file for allowing the MongoDB process to access the cgroup to determine the available memory on your system
cat > mongodb_cgroup_memory.te <<EOF
module mongodb_cgroup_memory 1.0;
require {
type cgroup_t;
type mongod_t;
class dir search;
class file { getattr open read };
}
#============= mongod_t ==============
allow mongod_t cgroup_t:dir search;
allow mongod_t cgroup_t:file { getattr open read };
EOF
Compile and load the custom policy modules by running this three commands
checkmodule -M -m -o mongodb_cgroup_memory.mod mongodb_cgroup_memory.te
semodule_package -o mongodb_cgroup_memory.pp -m mongodb_cgroup_memory.mod
semodule -i mongodb_cgroup_memory.pp
MongoDB process is now able to access the correct files with SELinux set to enforcing.
Update Firewalld
Update Firewalld policy to allow for replication on port 27017
sudo firewall-cmd --permanent --zone=public --add-port=27017/tcp
sudo firewall-cmd -reload
Create admin User
open mongo shell'
# mongo
use admin table
> use admin
switched to db admin
execute the command to create addmin user
db.createUser({user:"admin",pwd:"password",roles:[{role:"userAdminAnyDatabase",db:"admin"},{role:"dbAdminAnyDatabase", db:"admin"},{role:"readWriteAnyDatabase", db:"admin"},{role:"clusterAdmin", db:"admin"}]});
Test connection
mongo --authenticationDatabase admin -u <admin user> -p <password>
Configure IP address Binding
Stop MongoDB
sudo systemctl stop mongod
Edit /etc/mongod.config an change bindIP: from 127.0.0.1 to 0.0.0.0
bindIp: 0.0.0.0
Restart MongoDB
sudo systemctl start mongod
Verify change took effect
sudo netstat -naptu | grep 27017
YOU SHOULD SEE 0.0.0.0:27017
Configure MongoDB for TLS/SSL
Generate client and server certificates - not included in this blog. Refer to this blog
Edit /etc/mongod.conf file to update tls/ssl section
add the following under # network interfaces section
tls:
mode: requireTLS
allowInvalidHostnames: true
certificateKeyFile: /etc/ssl/mongodb/mongodb1.pem
CAFile: /etc/ssl/mongodb/mongoCA.pem
connect to TLS enabled database
mongo --tls --sslCAFile mongoCA.pem --sslPEMKeyFile coredClient.pem --host mongodb1 --username admin --password password --authenticationDatabase admin
- with replica -
mongo --ssl --sslCAFile mongoCA.pem --sslPEMKeyFile coredClient.pem --host mongo-replica/mongodb1:27017,mongo2:27017
Encryption at rest and auditing
create a base64 ecoded keyfile with the maximum 32 character string
openssl rand -base64 32 > mongodb-keyfile
copy the base64 encoded file to a desired location
cp mongoodb-keyfile /etc/mongodb/keyFile/
change the file permission of the base64 encoded file
chmown mongod:mongod /etc/mongodb/keyFile/mongoodb-keyfile
chmod 600 /etc/mongodb/keyFile/mongoodb-keyfile
update the mongod.conf file to include encryption at rest and audit logging
For encryption
security:
enableEncryption: true
encryptonKeyFile: /etc/mongodb/keyFile/mongoodb-keyfile
For Audit
auditLog:
destination: file
format: JSON
path: /var/log.mongodb/auditLog.json
Restart mongodb service
Configure mongo replication set
Edit the hosts file on both/all servers - for this blog we will use two servers
# sudo vi /etc/hosts
add the following ling
<ip_address> mongodb1
<ip_address> mongodb2
Save the /etc/hosts file exit vi
confirm mongodb instances can connect to each other prior to setting up replication
login to the first MongoDB server
mongo -host mongodb2 -port 27017
login to the second MongoDB server
mongo -host mongodb1 -port 27017
Edit mongod.conf file on all servers
uncomment the replication section and add the following
replicatin:
replSetName:"my-replica"
restart MongoDB on all the nodes
If mongo hostname are different from IP you might need to change the default configuration
use admin
config = {_id: "my-replica" , members [{ _id:0, host "mongodb1:27017" }]}
db.runCommand({replSetInitiate: config})
If the host name is the same as IP initiate using the following command( on mongodb1 server)
rs.initiate()
Add the second MongoDB instance (mongodb2) to the replica set
rs.add("mongodb2")
Check the status of the replica set with the following command
rs.status()
Verify the master (Primary) with the following command
rs.isMaster()
Test/Verify replication
on the primary server type the following
db.mycollection.insert({name: 'test'})
db.mycollection.find()
on the secondary instance type the following
db2 = (new Mongo('mongodb2:27017')).getDB('test')
db.setSecondaryOk()
db2.mycollection.find()
On the Primary MongoDB instance, type the
db.mycollection.drop() - output should be true
on the secondary instance type the following
db2.mycollection.find() - should show nothing displayed