MongoDB setup
1️⃣ Build the Docker Image
- (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. - Build the image:
-t mymongotags the image asmymongo.- 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.
--name mymongosets the container name tomymongo.-p 27017:27017maps the container’s MongoDB port to the same port on the host.-v mymongo_data:/data/dbuses a named Docker volume to persist MongoDB data.mymongo:6.0is the name:tag of the image you built.
3️⃣ Initialize the Replica Set
- Open a shell inside the running container:
- Initiate the replica set in
mongosh: - Verify the 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:
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 viamongo-initscripts 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. Yourrs.initiate({...})orrs.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.