Explore Knowledge Base

Setup MongoDB

08. 06. 2023
  • Connect to bastion:
ssh -i my-project.pem ubuntu@3.82.141.206

Setup MongoDB

  • Copy my-project.pem on the bastion
  • Connect to mongo instance:
ssh -i my-project.pem ubuntu@172.18.41.49

Setup MongoDB

  • Configure data disk:
sudo -i
mkfs.xfs /dev/xvdb
mkdir /var/lib/mongodb
disk=`blkid | grep xvdb | awk '{print $2}'`
echo "$disk /var/lib/mongodb xfs nodev,nosuid,noatime 0 2" >> /etc/fstab
mount -a
chown mongodb:mongodb /var/lib/mongodb
  • Setup mongodb:
apt install dirmngr gnupg apt-transport-https ca-certificates software-properties-common
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

apt update
apt install -y mongodb-org
systemctl enable mongod
systemctl restart mongod
  • Configure mongo:

Login to mongo:
mongo

Create users (Change “USER“,  “PASSWORD“,  ‘ADMIN_PASSWORD’on your data):

use admin
db.createUser({ user: "USER" , pwd: "PASSWORD", roles: ["userAdminAnyDatabase", "dbAdminAnyDatabase", "readWriteAnyDatabase"]})
var role = {
     role: "mongostatRole",
     privileges: [
       { resource: { cluster: true }, actions: [ "serverStatus" ] }
     ],
     roles: []
}
var auser = {
  "user" : 'admin',
  "pwd" : 'ADMIN_PASSWORD',
  roles : [
      {
          "role" : "userAdmin",
          "db" : "admin"
      },
      {
          "role" : "mongostatRole",
          "db" : "admin"
      }
  ]
}
use admin
db.createRole(role);
db.createUser(auser);
exit

Configure mongo:
Create mongodb.pem from your wildcard SSL certificate and key

cat cert.crt cert.key > mongodb.pem

Create ca.pem from your wildcard SSL certificate and SSL certificate chain

cat cert.crt cert_chain.pam > ca.pem

Create folder /admin on the server and copy mongodb.pem and ca.pem on it.

Modify /etc/mongod.conf:

storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true
systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log
net:
  port: 27017
  bindIp: 0.0.0.0
  ssl:
     mode: requireSSL
     PEMKeyFile: /admin/mongodb.pem
     CAFile: /admin/ca.pem
     disabledProtocols: "TLS1_0,TLS1_1"
     allowConnectionsWithoutCertificates: true

Add mongo host to hosts:

echo “127.0.0.1  mongo.your.domain” >> /etc/hosts

Restart mongo:

systemctl restart mongod

Check connections:

mongosh -ssl -host mongo.your.domain -username admin -password ADMIN_PASSWORD -authenticationDatabase admin

*You also need to setup any mongodb backups that are suitable for you.