Skip to content

Instantly share code, notes, and snippets.

@mahbubur001
Forked from royz/install_mongodb.md
Last active October 12, 2024 05:40
Show Gist options
  • Save mahbubur001/513eb01cbdc36d83c06f84fed1a37fe4 to your computer and use it in GitHub Desktop.
Save mahbubur001/513eb01cbdc36d83c06f84fed1a37fe4 to your computer and use it in GitHub Desktop.
Install MongoDb on ec2 and configure authentication for remote access

Install MongoDb on ec2 and configure authentication for remote access

1. Install and start mongo service [official docs]

1.1 Import the public key used by the package management system

wget -qO - https://www.mongodb.org/static/pgp/server-4.4.asc | sudo apt-key add -

1.2 Create a list file for MongoDB

echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/4.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.4.list

1.3 Reload local package database

sudo apt update

1.4 Install the MongoDB packages

sudo apt install -y mongodb-org

1.5 Start MongoDB

sudo systemctl start mongod

1.6 Verify that MongoDB has started successfully

sudo systemctl status mongod

1.7 Set MongoDB to start after a system reboot

sudo systemctl enable mongod

2. Create a user

2.1 Start mongo shell

mongo

2.2 Select the admin db (or any other db)

use admin

2.3 Create a new user with admin privilege to all databases (or set privilege to your own use-case)

db.createUser(
  {
    user: "<username>",
    pwd: "<password>",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
  }
)

for specific database

use targetDatabase

db.createUser(
  {
    user: "tUdmin",
    pwd: "password",
    roles: [ { role: "readWrite", db: "targetDatabase" } ]
  }
)

2.4 Exit out of mongo shell

exit

3. Enable authentication and Remote access

3.1 Specify the config file

sudo mongod --config /etc/mongod.conf

3.2 Edit the mongod config

sudo nano /etc/mongod.conf

3.3 Enable authorization

unser security, add the following:

security:
  authorization: enabled
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment