ryer.io

Setting Up a MongoDB Replica Set Locally with Enterprise Edition

TL;DR

  • Use MongoDB Enterprise Edition for client-side field-level encryption support.
  • Configure local MongoDB to mirror production environments.
  • Steps include stopping services, adjusting environment variables, and initializing the replica set.
  • Ensure proper command execution for starting services and setting up a replica set.

Today I dived into setting up a MongoDB replica set locally. The goal is to emulate our production environment as closely as possible. Despite not using Docker, this method provides a powerful way to achieve that.

Why Enterprise Edition?

First off, we need the MongoDB Enterprise Edition. It offers support for client-side field-level encryption (CSFLE) via the libMongoCrypt library. While the Community Edition has some encryption capabilities, the Enterprise Edition supports custom encryption, crucial for our needs.

Installation and Configuration

Install MongoDB Enterprise Edition: This edition includes necessary encryption functions.

Run Mongo Shell: After installation, ensure you have Mongo Shell (MongoSH) installed. Here’s a quick workflow I used:

  1. Stop Services:

    • Halt both the app server and MongoDB service. On macOS, I used:
      1
      
      brew services stop mongodb-enterprise
      
    • Alternatively, stop processes via:
      1
      2
      
      ps -aux | grep mongod
      sudo kill -9 [PID]
      
  2. Update Connection String:

    • Adjust your environment variable or hard-coded connection string to include:
      ?replicaSet=rs0
      
    • rs0 can be replaced with any name you prefer for the replica set.
  3. Restart MongoDB:

    • Start the service with the replica set configuration. Manually execute:
      1
      
      mongod --replSet rs0
      
    • Customize options depending on your local configurations (e.g., paths).

Initializing the Replica Set

To finalize the setup:

  • Run Mongo Shell: Open mongosh.

  • Initiate Replica Set:

    1
    
    rs.initiate();
    

    Check with:

    1
    
    rs.status();
    

Upon verifying that the replica set is active, exit the shell.

Conclusion

Start your application server, ensuring the connection string is accurate. By now, your local MongoDB instance should be a functioning single-node replica set. This setup lets you perform advanced operations like database transactions, mimicking a more robust production environment.

This journey into MongoDB’s replica set configuration was an enlightening technical exploration. With each step, the goal was a clear and seamless replication of a production setting locally. Now, I can focus on developing with a higher fidelity to production conditions.