Docker Compose setup for a MongoDB 8 single-node replica set with:
- Local host access on loopback only (
127.0.0.1) - Production Cloudflare Tunnel connector (
cloudflared) for remote access - Auth-enabled Mongo bootstrap via a custom init script
mongo:- MongoDB 8
- Replica set:
rs0 - Auth enabled
- Host bind:
127.0.0.1:${MONGO_RS_PORT}:27017
cloudflared:- Runs the production Cloudflare Tunnel token
- Reaches Mongo over internal Docker network
- Docker + Docker Compose plugin
- Cloudflare Tunnel already created
- Cloudflare route for
mongo-db.eodeluga.comset to:tcp://mongo:27017
Create .env for docker-compose.yml and .env.dev for docker-compose.dev.yml (both are gitignored).
Default compose example:
CLOUDFLARE_TOKEN=<your-cloudflare-tunnel-token>
MONGO_RS_HOST=mongo
MONGO_RS_PORT=27019
MONGO_INITDB_ROOT_USERNAME=admin
MONGO_INITDB_ROOT_PASSWORD=<strong-password>Dev compose example:
MONGO_RS_HOST=mongo
MONGO_RS_PORT=27017
MONGO_INITDB_ROOT_USERNAME=admin
MONGO_INITDB_ROOT_PASSWORD=<strong-password>For docker-compose.dev.yml, MONGO_PORT controls the host-published port and defaults to 27017. Keep MONGO_RS_PORT=27017 so the replica set advertises the same port Mongo actually listens on inside Docker.
Default compose, which uses the production tunnel:
docker compose up -dDev compose:
docker compose --env-file .env.dev -f docker-compose.dev.yml up -dCheck status:
Default compose:
docker compose ps
docker logs --tail 100 mongo-dbDev compose:
docker compose -f docker-compose.dev.yml ps
docker logs --tail 100 mongo-dbDefault compose exposes Mongo locally on 127.0.0.1:${MONGO_RS_PORT}.
Mongo Compass URI:
mongodb://<username>:<password>@127.0.0.1:${MONGO_RS_PORT}/?authSource=admin&directConnection=true
For dev compose, connect to 127.0.0.1:${MONGO_PORT:-27017} instead.
On your client machine, start a local forwarder:
cloudflared access tcp --hostname <your-cloudflare-tunnel-host> --url 127.0.0.1:37017
Then connect Compass to:
mongodb://<username>:<password>@127.0.0.1:37017/?authSource=admin&directConnection=true
MONGO_RS_PORTis the host-published port only.- Mongo inside Docker still listens on
27017. MONGO_PORTonly affectsdocker-compose.dev.yml.- If you change
.envor.env.dev, recreate the relevant containers:
docker compose up -d --force-recreate mongo cloudflared