Skip to content

Instantly share code, notes, and snippets.

@royz
Created January 31, 2021 17:11
Show Gist options
  • Save royz/6031d9b832e06917788f5c240a442611 to your computer and use it in GitHub Desktop.
Save royz/6031d9b832e06917788f5c240a442611 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" ]
  }
)

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