How to Create a Single-Node Replica Set Cluster for MongoDB Using Docker
If you’ve worked with Prisma or other ODMs for MongoDB, you might have run into a frustrating error when trying to use transactions while running the database on your local machine or even on a client’s VPS.
The reason?
MongoDB requires a replica set to support transactions. A standalone MongoDB instance does not allow multi-document transactions, which means any ORM/ODM like Prisma that relies on them will throw errors.
But here’s the good news: you don’t need a full multi-node cluster to get things working. You can spin up a single-node replica set using Docker. This setup is lightweight, works perfectly for local development, and is a great option for single-server deployments on a VPS.
In this post, I’ll walk you through the setup step by step.
Why Do We Need a Replica Set for Transactions?
So let’s fix that.
Step 1: Spin Up MongoDB with Docker Compose
Create a file called docker-compose.yml with the following configuration:
services:
mongo-srv:
image: mongo:latest
container_name: db-mongo
ports:
- '27017:27017'
restart: always
command: ['--replSet', 'rs0', '--bind_ip_all']
volumes:
- mongo-data:/data/db
volumes:
mongo-data:
Run the service:
docker compose up -d
Step 2: Initialize the Replica Set & Create a User
Once MongoDB is running, get into the container:
docker exec -it db-mongo mongosh
Now, initialize the replica set:
Recommended by LinkedIn
rs.initiate()
Switch to the admin database:
use admin
Create an application user:
db.createUser({
user: "app",
pwd: "password",
roles: [{ role: "root", db: "admin" }]
})
⚠️ Note: Execute each command one at a time.
Step 3: Connect with Your Application
Your connection string will look like this:
DATABASE_URL="mongodb://app:password@localhost:27017/mydb?directConnection=true&authSource=admin"
This connection string tells Prisma (or your chosen ODM) to connect directly to your single-node replica set with authentication.
Final Thoughts
With this setup, you get:
✅ Transaction support for Prisma and other ODMs
✅ Lightweight local development environment
✅ Easy-to-deploy solution for small VPS setups
✅ A foundation you can later expand into a full replica set if needed
If you’re working on apps where data consistency matters (like financial apps, bookings, or anything involving multiple related documents), this setup will save you from unexpected transaction errors.
#MongoDB #Docker #Prisma #DatabaseTransactions #ReplicaSet #BackendDevelopment #FullStackDevelopment #SoftwareEngineering #VPS #DevTips