Question: How do you configure a MongoDB replica set with authentication?

Answer

Configuring a MongoDB replica set with authentication involves several steps to ensure secure access to the database cluster. Below is a comprehensive guide:

Step 1: Initialize the Replica Set Without Authentication

First, you need to initialize your MongoDB replica set without authentication enabled. This simplifies the setup process and allows for the creation of the necessary administrative accounts. You can initiate the replica set by connecting to one of your MongoDB instances and using the rs.initiate() command.

mongo
rs.initiate({ _id: 'myReplicaSet', members: [ { _id: 0, host: 'mongodb0.example.com:27017' }, { _id: 1, host: 'mongodb1.example.com:27017' }, { _id: 2, host: 'mongodb2.example.com:27017' } ] })

Step 2: Create Administrative User

Once the replica set is initiated, create an administrative user that will have the rights to manage all aspects of the MongoDB databases.

Connect to your primary node:

mongo

Switch to the admin database:

use admin

Create an administrative user:

db.createUser({ user: 'myAdmin', pwd: 'password123', roles: [{ role: 'root', db: 'admin' }] })

Step 3: Enable Authentication

To enable authentication, you need to restart your MongoDB instances with the --auth flag (or equivalent configuration in your MongoDB config file). This enables MongoDB's role-based access control (RBAC) system.

Example configuration in /etc/mongod.conf:

security: authorization: enabled

Restart MongoDB service (the command might vary based on your operating system):

sudo systemctl restart mongod

Step 4: Connect With Authentication

After enabling authentication, all connections to the MongoDB server require proper credentials. Use the following command to connect to your database with the administrative user created earlier:

mongo -u myAdmin -p password123 --authenticationDatabase admin

Step 5: Additional User Creation

With authentication enabled and your administrative user in place, you can now securely create additional users with specific roles and permissions as required.

For example, to create a user with read and write access to the myDatabase database:

use myDatabase db.createUser({ user: 'myUser', pwd: 'password123', roles: [{ role: 'readWrite', db: 'myDatabase' }] })

By following these steps, you will have successfully configured a MongoDB replica set with authentication, enhancing the security of your database cluster.

Was this content helpful?

Start building today

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.