Skip to content

Latest commit

 

History

History
142 lines (112 loc) · 2.36 KB

MongoDB_Setup_on_VPS.md

File metadata and controls

142 lines (112 loc) · 2.36 KB

Setup MongoDB on VPS

Install MongoDB

  sudo apt-get install gnupg curl
  curl -fsSL https://www.mongodb.org/static/pgp/server-7.0.asc | \
   sudo gpg -o /usr/share/keyrings/mongodb-server-7.0.gpg \
   --dearmor

Create the MongoDB list file.

echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-7.0.gpg ] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/7.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list

Update package lists and install MongoDB.

  sudo apt-get update
  sudo apt-get install -y mongodb-org

Start and enable MongoDB service.

  sudo systemctl daemon-reload
  sudo systemctl start mongod
  sudo systemctl enable mongod

Verify that MongoDB has started successfully.

  sudo systemctl status mongod

MongoDB URI to connect with projects.

  mongodb://127.0.0.1:27017

Configure MongoDB Authentication ( Optional )

Allowing MongoDB through firewall

Enable firewall

sudo ufw enable

Check Port is Allowed through Firewall

  sudo ufw status

If Port is not Allowed then Allow it through Firewall

  sudo ufw allow 27017
   sudo ufw allow 'OpenSSH'

Restart MongoDB

  sudo service mongod restart

Secure MongoDB by setting up Super User.

Connect to MongoDB shell

  mongosh

Show database

  show dbs

Change to admin database

  use admin

Create superuser with all privileges

  db.createUser({user: "username-here" , pwd: passwordPrompt() , roles: ["root"]})

Now Exit mongosh shell

  .exit

Enable Authorization removing comment

  sudo nano /etc/mongod.conf
  security:
    authorization: enabled

Restart MongoDB

  sudo service mongod restart

To Access Mongo Shell as Super User use this command:

  mongosh --port 27017 --authenticationDatabase "admin" -u "username-here" -p "password-here"

Create Database & User for project:

  use database_name
  db.createUser({user:"username_here", pwd:passwordPrompt(), roles:[{role:"readWrite", db:"database_name"}]})

Now Exit mongosh shell

  .exit

MongoDB URI to Connect with projects:

  mongodb://username-here:password-here@127.0.0.1:27017/database_name