
Halo, kalau kamu merasa tulisan saya ngebantu kamu, kamu bisa ucapkan terima kasih lewat saweria.
Hello, if you find this article helpful, you can express your gratitude through saweria.
Ini saya ambil dari jawaban Stackoverflow - Mongo container with a replica set with only one node in docker-compose, setelah seharian mencari dan ga dapat tutorial yang works, jadi saya tulis saja disini.
Kasus
Perlu Mongo Replica tapi ga ada resource (cuma ada 1 server/mau coba di local laptop aja)
Mongo Cluster
- Buat
Dockerfile, isi dengan
#since i only need mongo5, i didnt test with another version
FROM mongo:5.0
RUN echo "rs.initiate({'_id':'rs-test', members: [{'_id':1, 'host':'127.0.0.1:27017'}]});" > "/docker-entrypoint-initdb.d/init_replicaset.js"
#create key file, it a must!
RUN echo "12345678euysusahbingit" > "/tmp/key.file"
RUN chmod 600 /tmp/key.file
RUN chown 999:999 /tmp/key.file
CMD ["mongod", "--replSet", "rs-withdraw", "--bind_ip_all", "--keyFile", "/tmp/key.file"]
- Buat
docker-compose.yml
services:
mongo-replica:
build: .
image: mongo-replica
container_name: mongo-1
restart: always
logging:
driver: none
ports:
- 27017:27017
healthcheck:
test: test $$(echo "rs.initiate().ok || rs.status().ok" | mongo -u usernameKamu -p passWord --quiet) -eq 1
interval: 10s
start_period: 30s
environment:
MONGO_INITDB_ROOT_USERNAME: usernameKamu
MONGO_INITDB_ROOT_PASSWORD: passWord
MONGO_INITDB_DATABASE: testDB
deploy:
resources:
limits:
memory: 1G
networks:
- mongo-net
networks:
mongo-net:
name: mongo-replica-net
- Jalankan
docker compose up -d

Single Instance Read as Primary
