MongoDB replica set enable some essentials features of traditional database such as transactions. For development it may be convenient to setup a MongoDB container with replica set. Doing so in a single docker-compose file can be challenging. We will see how to do it today in the simplest way possible.
Multi nodes replication vs single node replication
If you searched docs about replica set you probably came across this figure:
Which is indeed how basic replica set with multi node works. The issue is that multi node setup in docker is really challenging because of hostname resolution. What this diagram doesn’t tell you is that replica set also work with a single MongoDB node! However, this is not advised for a production setup since it would break many replica set promise such as high availability and redundancy. But we don’t care since our setup is intended for development or testing purposes.
The docker-compose file
What this file does is declare a mongo service based on the docker image mongo 4.4, you can use any version > 4.0 it should works. We expose and map the default MongoDB port on 27017. When the container start we specify our replica set name, rs0
using the command instruction. Finally, to issue the configuration of our replica set to our running MongoDB instance we use a healthcheck.
Then you simply start the service using docker-compose up
. And you can connect to it using connection string mongodb://127.0.0.1:27017/<DB_NAME>
.
That’s all!