Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

A Docker Compose learning cluster needs three MongoDB roles: a config-server replica set to hold cluster metadata, at least one shard replica set to store application data, and a mongos router for clients. For local development, you can run one container for each role on a shared Compose network. That demonstrates how the parts discover one another, but it is not a highly available or production-ready deployment.

Understand the topology before writing Compose

A sharded cluster distributes data across shards at the collection level. Each shard must be a replica set. A config-server replica set stores metadata such as chunk placement, and mongos uses that metadata to route client operations. As the MongoDB Manual puts it, “The mongos provides the only interface to a sharded cluster from the perspective of applications.” Connect applications to a router, not directly to shard members.

  • Shard replica set: stores a portion of the sharded data. A one-member set is sufficient to explore the wiring, but has no member redundancy.
  • Config-server replica set: stores metadata needed to operate the cluster. Its availability affects cluster operations.
  • mongos router: accepts client requests and routes them to the relevant shard or shards.

Sharding is useful when data size or workload needs distribution across machines; it also adds infrastructure and operational work. The shard key determines how a collection is distributed and whether queries can be targeted. A query that omits the shard key, or the usable prefix of a compound shard key, may be broadcast to every shard rather than routed to just one.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose a development topology or a production design

Design Use it when Tradeoff
One config-server replica set, one shard replica set, one mongos Learning, local integration, or experimenting with routing and shard keys Reduced test/development topology; a single member or Docker host can be a failure point
Dedicated config-server replica set Metadata isolation is operationally desirable or required by a feature More replica-set members and services to operate
Config shard (MongoDB 8.0 and later) Reducing node count is useful and the deployment’s feature needs allow combining roles Application data and cluster metadata share a replica set; this does not suit features that require isolation

MongoDB’s reduced topology is documented for testing and development, not as a production substitute. Production guidance calls for a three-member config-server replica set, three members per shard replica set, and one or more routers, with replica-set members distributed across failure domains or data centers where possible. Multiple routers can support availability and scaling, but they communicate frequently with config servers; MongoDB 8.0 guidance notes that performance may degrade as router count increases. Adding containers on one Docker host does not protect a cluster from that host failing.

When a config shard is an option

Starting with MongoDB 8.0, an eligible config-server replica set can also store application data as a config shard. MongoDB says this has no measurable performance impact at low shard counts, but a dedicated config-server replica set keeps metadata isolated from application data. The manual identifies Queryable Encryption collections and on-premises queryable backups among features that require that isolation. Check the requirements for the features you intend to use before combining the roles; a config shard is a version-specific option, not a universal default.

Compose a minimal learning cluster

This example runs one config-server member, one shard member, and one router on a shared network. It is a wiring example, not a production deployment: it has no member redundancy, authentication, or failure-domain separation. Set MONGODB_IMAGE to one verified, explicit MongoDB image tag or digest, and use the same image for every service. Pinning the image makes the setup reproducible; do not treat a moving major-version tag as an immutable release.

Also popular on Amazon
2 Bay DIY NAS Kit, x86 Home Server, Intel Quad-Core, 16GB RAM, | Dual SATA, PCIe x4 Expansion, Docker Ready, Plex, Home Assistant
  • 【Build Your Own NAS & Homelab — Not Just Storage】 More than a traditional NAS, ZimaBlade 7700 is a flexible x86 mini server for building your own homelab, personal cloud, or Docker host. Perfect for DIY NAS, self-hosting, container apps, and even retro systems — not limited like typical ARM-based NAS devices.
  • 【x86 Platform — Broad Compatibility, Real Freedom】 Powered by an Intel quad-core x86 processor, it runs a wide range of operating systems and software with native compatibility. Ideal for Linux, Docker, CasaOS, and more — designed for flexibility and experimentation rather than locked-down appliance use.
  • 【16GB RAM for Smooth Multi-Service Workloads】 Handle file sharing, media streaming, backups, and multiple lightweight services at once. Optimized for low-power, always-on operation — a great fit for home labs and personal servers running 24/7.
  • 【Smooth 4K Media Streaming — Plex Direct Play Ready】 Stream your personal media library smoothly with Plex and similar media servers. Supports 4K playback on compatible devices via direct play, delivering a reliable home media experience without the need for heavy transcoding.
  • 【Complete 2-Bay NAS Kit — Ready to Build】 Includes power supply, 16GB RAM, metal drive cage for 2 HDD/SSD, and dual SATA cables — everything you need to start building your own NAS right out of the box.
services:
  cfg1:
    image: ${MONGODB_IMAGE:?Set MONGODB_IMAGE to a pinned MongoDB image tag or digest}
    command: ["mongod", "--configsvr", "--replSet", "cfgRS", "--port", "27019", "--bind_ip_all"]
    volumes:
      - cfg1-data:/data/configdb
    networks: [mongo-net]

  shard1:
    image: ${MONGODB_IMAGE:?Set MONGODB_IMAGE to a pinned MongoDB image tag or digest}
    command: ["mongod", "--shardsvr", "--replSet", "shardRS", "--port", "27018", "--bind_ip_all"]
    volumes:
      - shard1-data:/data/db
    networks: [mongo-net]

  mongos:
    image: ${MONGODB_IMAGE:?Set MONGODB_IMAGE to a pinned MongoDB image tag or digest}
    command: ["mongos", "--configdb", "cfgRS/cfg1:27019", "--port", "27017", "--bind_ip_all"]
    depends_on: [cfg1]
    networks: [mongo-net]

volumes:
  cfg1-data:
  shard1-data:

networks:
  mongo-net:
    driver: bridge

The service names cfg1 and shard1 are the hostnames that members advertise to each other. Compose’s network DNS resolves those names between containers. The ports are distinct inside their respective containers; no host ports are published in this example. If you need to connect from the host, add a deliberate host-port mapping for mongos and limit it to the local machine for a development setup. Do not advertise localhost as a member address: inside a container, it refers to that container itself.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The MongoDB Docker Official Image accepts arguments passed to mongod, as shown here, or can use a mounted configuration file passed with --config. Confirm the image’s current configuration syntax and the chosen release’s supported options before adapting the example. The MongoDB Docker tutorial demonstrates shared-network hostname use and replica-set initialization, but its example uses MongoDB 5 and is not a complete modern sharded-cluster Compose recipe.

Initialize the replica sets and attach the shard

Compose’s depends_on controls startup order; it does not mean a MongoDB process is ready to accept replica-set commands. Start the services, inspect their logs, and wait for each mongod to be reachable before initializing it.

  1. Start the services: run docker compose up -d. Check docker compose logs cfg1 shard1 mongos for startup errors. If the router starts before its config server is ready, allow it time to connect and check its logs again.
  2. Initialize the config-server replica set once: run docker compose exec cfg1 mongosh --port 27019, then enter rs.initiate({_id: "cfgRS", configsvr: true, members: [{_id: 0, host: "cfg1:27019"}]}). Use the set name and hostname configured in Compose.
  3. Initialize the shard replica set once: run docker compose exec shard1 mongosh --port 27018, then enter rs.initiate({_id: "shardRS", members: [{_id: 0, host: "shard1:27018"}]}). Wait for each set to elect its primary; check with rs.status() in that member’s shell.
  4. Add the shard through the router: connect with docker compose exec mongos mongosh --port 27017, then run sh.addShard("shardRS/shard1:27018"). The replica-set name and address must match the initialized shard.
  5. Enable sharding for the intended data: in the router shell, run sh.enableSharding("appdb") and then, after choosing a suitable key for the collection, run a command such as sh.shardCollection("appdb.events", {tenantId: "hashed"}). The tenantId example is illustrative, not a universal recommendation; select the key based on the collection’s access patterns and distribution needs.
  6. Verify through mongos: run sh.status() or db.adminCommand({listShards: 1}) in the router shell. Confirm the shard appears and that your target database and collection have the expected sharding state.

Replica-set initialization is a one-time operation for a fresh data directory. If a command reports that a set is already initialized, inspect its configuration and status instead of repeatedly initiating it. The image’s initialization environment variables and scripts are also applied only when the data directory is empty; changing them does not reconfigure existing database files on container startup.

Also popular on Amazon
Dell PowerEdge R730xd Server 24B SFF 2U, 2X Intel Xeon E5-2690 v4 2.6Ghz (28-cores Total), 128GB DDR4 RAM, 4X 1.2TB 10K SAS 2.5” 12Gb/s HDD, H730P 2GB RAID, NIC 10Gb + I350 1Gb (Renewed)
  • Dell PowerEdge R730xd 24B SFF 2U Server
  • 2x Intel Xeon E5-2690 v4 2.6Ghz 14-Core (28-cores Total)
  • 128GB DDR4 RAM – 4x 1.2TB 10K SAS 2.5” 12Gb/s
  • Dell H730P mini 2GB 12Gb/s RAID
  • 2x 750W PSU - 2x 10Gb SFP+ 2x 1Gb (RJ45) NIC
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Keep names, data, and client connections consistent

Use resolvable member addresses

Every MongoDB component must be able to resolve the hostnames advertised in replica-set configurations and the config-server connection string. In Compose, stable service names on the same user-defined network are a practical choice. If localhost or its IP address is used in a cluster host identifier, MongoDB’s deployment guidance requires that identifier to be used consistently by the other MongoDB components as well; that is generally not the right identity for peer containers.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Persist database files

The named volumes in the example preserve config-server and shard files when containers are replaced. Removing a container is different from deleting its named volume. Treat volume deletion as data deletion, and make backups before changes that could affect stored data.

Also popular on Amazon
Sale
Ateco Dough Docker, White , 5.25-Inches wide | Eliminate air pockets in dough
  • Ateco #1357 Dough Docker for use with pastry or pizza dough for best baked results
  • Roll over pizza dough, pie dough, pastries before baking, the small depressions help reduce blistering or air pockets from forming while crust bakes
  • Measures 5.25-Inches wide, 2.25-Inch diameter, 8.25-Inches long including handle
  • Hand wash suggested for best results; made from high impact plastic
  • Family owned and operated since 1905, Ateco has produced specialized professional quality baking and decorating tools for professional pastry chefs and discerning home bakers alike

Use the router as the application endpoint

Applications and administrative clients that need cluster-level behavior should connect to mongos. For the sample stack, that endpoint is mongos:27017 from another container on mongo-net; a host-side endpoint exists only if you explicitly publish a port. Direct shard connections do not provide the cluster routing interface.

Harden and operate beyond local experimentation

Do not expose an unauthenticated cluster to a publicly reachable interface. Before making a deployment accessible beyond a trusted local environment, configure authentication, use internal/member authentication between cluster members, restrict network access, protect credentials, and plan backups. A Compose file on one host demonstrates service wiring; it cannot provide host-level fault tolerance.

Config-server availability is especially important. If its replica set loses its primary and cannot elect another, metadata becomes read-only and chunk migrations and splits stop. Complete config-server unavailability can make the cluster inoperable. Do not edit the config database directly, and back it up before config-server maintenance.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For production planning, use MongoDB’s production topology guidance rather than scaling the learning file by simply adding services. Place replica-set members across independent failure domains where possible, choose router capacity deliberately, and validate the resulting configuration against the MongoDB version and features you plan to run.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply. Prices as of November 17, 2026 7:31 pm GMT.