Skip to content

Instantly share code, notes, and snippets.

@tatumroaquin
Last active April 7, 2023 15:58
Show Gist options
  • Save tatumroaquin/22f5c28b2657a16f84f7ef994ada3469 to your computer and use it in GitHub Desktop.
Save tatumroaquin/22f5c28b2657a16f84f7ef994ada3469 to your computer and use it in GitHub Desktop.

MongoDB Standalone Config

MongoDB Resource Specification

  1. LXC Container
  2. Minimum 2 CPU Cores (2 threads are needed to run the TTL Monitor.)
  3. 10GB HDD

1. Create admin user

$ mongosh
> use admin
> db.createUser(
  {
    user: "myUserAdmin",
    pwd: passwordPrompt(), // or cleartext password
    roles: [
      { role: "userAdminAnyDatabase", db: "admin" },
      { role: "readWriteAnyDatabase", db: "admin" }
    ]
  }
)

2. Enable authorization

# /etc/mongodb.conf
security:
  authorization: enabled

3. Check authentication

Login before connection

$ mongosh --authenticationDatabase 'admin' -u <user> -p
Enter password:
or
$ mongosh --authenticationDatabase 'admin' -u <user> -p <pass>

Login after connection

$ mongosh
> use admin
> db.auth(<user>, passwordPrompt())
or
> db.auth(<user>, <pass>)

1. Generate keyfile with OpenSSL

openssl rand -base64 756 > /opt/mongodb/keyfile
sudo chown mongodb:mongodb /opt/mongodb/keyfile
sudo chmod 400

2. Specify keyfile to mongodb.conf

# /etc/mongodb.conf
security:
  authorization: enabled
  keyFile: /opt/mongodb/keyfile

3. Add Replica Set Name

# /etc/mongodb.conf
replication:
  replSetName: <name>

4. Restart MongoDB service

sudo systemctl restart mongodb

5. Authenticate to admin user

$ mongosh
> use admin
> db.auth(<user>, passwordPrompt())

6. Grant admin the clusterAdmin role

> db.grantRolesToUser(<user>, [
  {role: 'clusterAdmin', db: 'admin'}
])

7. Add self to replica members

> rs.initiate()

errors:

"WiredTiger error","attr":{"error":13,"message":"[1662831911:129518][1630:0x7f062b617ec0], wiredtiger_open: __posix_open_file, 808: /var/lib/mongodb/WiredTiger.turtle: handle-open: open: Permission denied"

sudo su
chown -R mongodb:mongodb /var/lib/mongodb

"Read security file failed","attr":{"error":{"code":30,"codeName":"InvalidPath","errmsg":"Error reading file /path/to/mongodb/keyfile: Permission denied"

sudo mkdir -p /opt/mongodb/
sudo mv /path/to/mongodb/keyfile /opt/mongodb/
sudo chown -R mongodb:mongodb /opt/mongodb
sudo chmod 400 /opt/mongodb/keyfile
  • I do not fully understand why this error occurs and why it can't access the user directory.
  • But it seems to alleviate permission errors when it is moved to a different directory within the system.

sources:

https://stackoverflow.com/questions/53478123/mongodb-can-not-start-because-of-wiredtiger-turtle-permissions
https://www.digitalocean.com/community/tutorials/how-to-configure-keyfile-authentication-for-mongodb-replica-sets-on-ubuntu-20-04

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