Skip to content

Instantly share code, notes, and snippets.

@gavvvr
Created July 8, 2022 19:26
Show Gist options
  • Save gavvvr/67b9e6a822b8f98d40769da56d1496e9 to your computer and use it in GitHub Desktop.
Save gavvvr/67b9e6a822b8f98d40769da56d1496e9 to your computer and use it in GitHub Desktop.
Enabling mongo transactions using docker-compose

If you develop against of containerized mongo instance using the official Docker Mongo image and make attempt to use transactions, you will most probably face the following error:

com.mongodb.MongoCommandException: Command failed with error 20 (IllegalOperation): 'Transaction numbers are only allowed on a replica set member or mongos' on server localhost:28017. The full response is {"ok": 0.0, "errmsg": "Transaction numbers are only allowed on a replica set member or mongos", "code": 20, "codeName": "IllegalOperation"}

This single docker-compose.yaml will solve the problem by creating replica set out of single node.

version: '3.9'
services:
mongodb:
image: mongo:5
command: --replSet rs0
ports:
- "28017:27017"
environment:
MONGO_INITDB_DATABASE: attachment-api-local-dev
healthcheck:
test: echo 'db.runCommand("ping").ok' | mongo localhost:27017/admin --quiet
interval: 2s
timeout: 3s
retries: 5
mongo-init:
image: mongo:5
restart: "no"
depends_on:
mongodb:
condition: service_healthy
command: >
mongo --host mongodb:27017 --eval
'
rs.initiate( {
_id : "rs0",
members: [
{ _id: 0, host: "localhost:27017" }
]
})
'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment