Skip to content

MongoDB setup

1️⃣ Build the Docker Image

  1. (Optional) Add any initialization scripts inside a folder named mongo-init (as referenced in the Dockerfile). These scripts will be automatically executed when the container first starts.
  2. Build the image:
    docker build -t my-mongo .
    
  3. -t mymongo tags the image as mymongo.
  4. The final . indicates the Dockerfile is in the current directory.

2️⃣ Run the MongoDB Container

When running a MongoDB container, you typically want to: - Expose port 27017 so you can connect externally. - Persist data using a Docker volume or bind mount.

     docker run -d --name mongo-container -p 27017:27017 my-mongo
  • --name mymongo sets the container name to mymongo.
  • -p 27017:27017 maps the container’s MongoDB port to the same port on the host.
  • -v mymongo_data:/data/db uses a named Docker volume to persist MongoDB data.
  • mymongo:6.0 is the name:tag of the image you built.

3️⃣ Initialize the Replica Set

  1. Open a shell inside the running container:
    docker exec -it mymongo mongosh
    
  2. Initiate the replica set in mongosh:
    rs.initiate()
    
  3. Verify the status:
    rs.status()
    
    Look for "myState": 1 (which indicates PRIMARY on a single-node setup).

Why a Replica Set?

MongoDB’s Kafka connectors require the database to be in a replica set mode—even if you’re using a single node—so that the Oplog is available for change streams.


4️⃣ (Optional) Check Initialization Scripts

If you placed any .js or .sh scripts in mongo-init/ inside your build context:

  • These scripts are copied to /docker-entrypoint-initdb.d/ by the Dockerfile.
  • MongoDB will automatically run them on the first container startup only.
  • Common uses include creating users, enabling authentication, or pre-seeding the database.

5️⃣ Connect to Your MongoDB

From outside the container, you can connect using the host machine’s IP (or localhost if you’re on the same machine) and port 27017:

mongosh "mongodb://localhost:27017"

Or if you need to specify replica set details (in a multi-node scenario), you’d include those in the connection string, e.g. mongodb://mongo1:27017,mongo2:27017/?replicaSet=rs0.


6️⃣ Additional Considerations

  • Enabling Authentication:
    If you need a username/password, configure it either via mongo-init scripts or by logging into the container, creating an admin user, and enabling --auth.
  • Multi-Node Replica Set:
    For production or high-availability scenarios, run multiple MongoDB containers/nodes and configure them to replicate. Your rs.initiate({...}) or rs.add() commands will include each node’s hostname and port.
  • Resource Usage:
    Make sure your Docker host has enough memory and CPU for MongoDB, especially if you handle large datasets or heavy workloads.