Cloud Native › Swarm

Choosing between Docker Compose, Swarm, and Kubernetes

Compare Docker Compose, Swarm, and Kubernetes across networking, storage, secrets, and recovery based on local lab tests to choose the right fit by scale.

Choosing between Docker Compose, Swarm, and Kubernetes

Once a single-host Docker Compose stack outgrows one server, you have to decide whether to step up to Docker Swarm or jump straight to Kubernetes. This post compares the same web and database stack across all three orchestrators using local lab tests—covering networking, storage, secrets, recovery, and clear inflection points by scale.

Every behavior and measurement in this post comes from isolated local labs: Docker Compose on Docker Engine 29.9.3 with Compose v5.7.1, Docker Swarm on a 3-node DinD cluster running Engine 29.10.1, and Kubernetes on a 3-node kind v0.33.0 cluster running Kubernetes v1.37.0 with Envoy Gateway v1.10.0.

Comparing the three orchestrators at a glance

All three tools run standard OCI container images, but they draw very different operational boundaries. Docker Compose declares a multi-container stack on one host, Docker Swarm turns Docker Engine itself into a lightweight multi-node cluster, and Kubernetes provides a declarative control-loop platform built for multi-team scale.

Here is how the three compare when you run the same web API and database stack across them.

DimensionDocker ComposeDocker SwarmKubernetes
Execution scopeSingle hostMulti-node (built into Engine)Multi-node (dedicated control plane)
Networking & DNSPer-project bridge + 127.0.0.11VXLAN Overlay + VIP / DNSRRPod-per-IP (CNI) + EndpointSlice + CoreDNS
External routingHost -p bindings (add your own reverse proxy)Ingress Routing Mesh (SNAT) vs mode=hostNodePort / LoadBalancer + Gateway API (HTTPRoute)
Storage & statefulHost-local Named Volume / Bind MountNode-bound local volume (node.labels pin or external DB)Dynamic StorageClass / PV / PVC + StatefulSet
Secret isolationRead-only host file bind mountRaft-encrypted, immutable tmpfs mountAPI-managed Secret (extensible to KMS / External Secrets)
Failure recoveryrestart on process exit only (unhealthy stays running)Reschedules tasks across nodes on failure or drain1s control-loop self-healing + 3 probes + QoS
Deploy & rollbackup -d recreates containers (no built-in rolling update)start-first rolling update + service rollbackDeployment RollingUpdate + rollout undo + canary
Operational overheadVery low (single compose.yaml)Low (extends standard Docker CLI)High (CNI, CSI, Gateway, RBAC, GitOps)

Two real inflection points stand out in this matrix: leaving a single host, and needing L7 traffic control, dynamic storage, or fine-grained lifecycle management. The next sections break down how each layer behaves in practice.

How networking and traffic routing diverge

The first architectural gap shows up in how containers discover each other and accept external traffic.

Docker Compose creates an isolated bridge network per project and resolves service names through embedded DNS (127.0.0.11). To connect separate Compose stacks, you attach both to a pre-created external: true network. To lock down a database tier, you place it on an internal: true network—in local tests, a container attached only to an internal network gets no default via gateway in ip route, so outbound calls to 1.1.1.1:80 fail immediately with Network unreachable. You can see the full isolation tests in my note on Docker Compose internal and external networks.

Docker Swarm spans multiple nodes using VXLAN overlay networks. The default vip endpoint mode exposes one virtual IP backed by IPVS round-robin, while dnsrr returns individual task IPs directly as DNS A records (and rejects mode=ingress port publishing). For external traffic, Swarm’s Ingress Routing Mesh (mode=ingress) forwards requests even when they hit a node running zero tasks—in my 3-node DinD test, hitting swarm-mgr1:8080 reached both worker tasks, but Ingress SNAT rewrote RemoteAddr to the ingress sandbox IP (10.0.0.2). Switching to mode=host preserved the real client IP (172.22.0.5), yet hitting the taskless manager node returned Connection refused. I documented both packet paths in the Swarm overlay and ingress routing mesh breakdown.

Kubernetes assigns every Pod a cluster-routable IP via CNI and decouples callers from ephemeral Pod IPs using Service (ClusterIP, NodePort, Headless), EndpointSlice, and CoreDNS (10.96.0.10). When a Pod is deleted and replaced with a new IP (10.244.1.8 → 10.244.1.11), the ClusterIP stays fixed and EndpointSlice updates automatically. For L7 HTTP routing after ingress-nginx reached EOL in March 2026, Gateway API (GatewayClass, Gateway, HTTPRoute) cleanly separates cluster infrastructure from application routing rules. On kind with Envoy Gateway v1.10.0, a standard HTTPRoute with zero vendor annotations handled /v1 and /v2 path routing, X-Canary: true header routing, and an 80/20 weighted canary split (measured 80:20 and 81:19 across two 100-request runs). See the Kubernetes Gateway API canary routing guide for the full manifests.

Storage, secrets, self-healing, and shutdown

Beyond networking, day-two operations hinge on how each tool handles stateful data, secrets, and failure recovery.

Storage and stateful workloads

  • Docker Compose: Uses host-local Named Volumes and Bind Mounts. Because every container stays on the same machine, cross-node volume attachment isn’t a problem.
  • Docker Swarm: Ships without a built-in distributed volume driver, so Named Volumes stay tied to the node where they were created. In the 3-node DinD lab, draining swarm-wrk1 rescheduled an unpinned stateful task onto swarm-wrk2 in 12 seconds—but mounted a brand-new empty /data volume while the original file remained stranded on swarm-wrk1. Adding --constraint 'node.labels.db==primary' stopped the task from moving, holding it Pending (no suitable node) to prevent empty-database initialization and split-brain until swarm-wrk1 returned. In production Swarm clusters, moving RDBMS workloads to an external managed database or dedicated host is usually the safest choice; see running stateful services on Docker Swarm.
  • Kubernetes: Separates storage requests from provisioning with StorageClass, PV, and PVC. Mounting a single ReadWriteOnce (RWO) PVC across a multi-node Deployment blocks the second Pod—at scheduling time on local-path provisioners (didn't match PersistentVolume's node affinity), or at attach time on cloud block storage like EBS (Multi-Attach error). Using a StatefulSet with volumeClaimTemplates gives each ordinal Pod (stateful-app-0, stateful-app-1) its own PVC and stable DNS record, so deleting and recreating stateful-app-0 reattaches the exact same volume intact (Kubernetes PV, PVC, and StatefulSet lab).

Secret isolation and rotation

  • Docker Compose: The root .env file only interpolates compose.yaml—it doesn’t auto-inject variables into container environments. Using secrets with *_FILE variables (such as POSTGRES_PASSWORD_FILE) keeps plaintext out of docker inspect Config.Env, but standalone Compose still implements secrets as a read-only host bind mount (Type: "bind", RW: false) rather than encrypted memory (Docker Compose .env and secrets precedence).
  • Docker Swarm: Stores docker secret encrypted in the Raft log and mounts it inside /run/secrets/ as read-only tmpfs (RAM-backed). Because Swarm secrets and configs are immutable, you rotate them by creating a new version (app_secret_v2) and swapping via --secret-rm/--secret-add with --update-order start-first. Across 12 HTTP polls at 0.5-second intervals during rotation, I observed 0 failed requests, and docker service rollback restored v1 in 13 seconds.
  • Kubernetes: Manages ConfigMap and Secret per namespace and integrates with KMS encryption-at-rest or External Secrets Operator when you need centralized secret stores like Vault or AWS Secrets Manager.

Health checks, self-healing, and graceful shutdown

  • Docker Compose: A failing healthcheck marks a container unhealthy and gates depends_on: condition: service_healthy, but Compose won’t automatically restart an unhealthy container unless the process actually exits.
  • Docker Swarm: Reconciles desired replica counts across nodes and supports start-first rolling replacements and rollback.
  • Kubernetes: The Deployment → ReplicaSet control loop replaced a manually deleted Pod in roughly 1 second with a fresh name and IP (verifying Pods and Deployments on kind). Three separate probes divide responsibilities cleanly: startupProbe shields an 8-second slow startup from a 4-second livenessProbe, a failing readinessProbe pulls the Pod from EndpointSlice (ready: false) with RESTARTS=0, and a failing livenessProbe triggers a kubelet restart. Resource requests/limits classify Pods into Guaranteed, Burstable, or BestEffort QoS tiers (terminating memory overruns cleanly as OOMKilled exit 137), and a preStop hook ran for its full 5.013 seconds before SIGTERM reached the main process (+0.016 seconds) so in-flight traffic could drain.

Manifest footprint for the same web service

Even a minimal web service shows how differently each tool structures configuration (Compose runs a single instance due to host port binding, while Swarm and Kubernetes declare two replicas).

1
2
3
4
5
6
# 1) Docker Compose (compose.yaml) — single host, modularizable with include
services:
  web:
    image: nginx:1.27-alpine
    ports: ["8080:80"]
    restart: unless-stopped
1
2
3
4
5
# 2) Docker Swarm — multi-node replicas + start-first rolling update in one command
docker service create --name web --replicas 2 \
  --publish mode=ingress,published=8080,target=80 \
  --update-order start-first --update-parallelism 1 \
  nginx:1.27-alpine
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# 3) Kubernetes — Deployment + Service (+ separate Gateway/HTTPRoute for L7)
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
spec:
  replicas: 2
  selector:
    matchLabels: { app: web }
  template:
    metadata:
      labels: { app: web }
    spec:
      containers:
        - name: nginx
          image: nginx:1.27-alpine
          ports: [{ containerPort: 80 }]
---
apiVersion: v1
kind: Service
metadata:
  name: web
spec:
  selector: { app: web }
  ports: [{ port: 80, targetPort: 80 }]

Kubernetes splits workloads, service discovery, and ingress routing into distinct resources. That adds upfront YAML, yet it lets teams swap proxies, delegate RBAC, and automate rollouts independently as the system grows.

Migration inflection points by team and service scale

When single-host Compose stops being enough, the right next step depends less on raw node count and more on team capacity and platform features.

flowchart TD
    A["Single host enough?"] -->|"Yes"| B["Docker Compose"]
    A -->|"No (multi-node HA)"| C["Need canary, StatefulSet, multi-team?"]
    C -->|"No (lightweight HA, external DB)"| D["Docker Swarm"]
    C -->|"Yes (cloud-native scale)"| E["Kubernetes (managed first)"]

Here is a practical decision matrix by team and service stage.

Stage & team sizeRecommended toolWhy it fitsRecommended stateful strategy
Solo, homelab, early MVP (1 server, brief restarts OK)Docker Composecompose.yaml + include keeps local and prod aligned with minimal ops overheadHost Named Volumes + scheduled backups
Small team, 2–5 nodes (no dedicated platform engineer)Docker SwarmReuses Docker CLI and Compose concepts for multi-node HA, tmpfs secrets, and start-first updatesExternal managed DB (RDS, Cloud SQL) or node.labels pinning
Growing or multi-team production (variable load, frequent deploys)Kubernetes (EKS/GKE/AKS)Gateway API canaries, 3 probes + preStop, dynamic PVCs & StatefulSet, HPA, RBAC, GitOpsManaged cloud DB first; StatefulSet only for necessary in-cluster state

Moving from Compose to Swarm has the lowest friction: you keep almost the same compose.yaml format via docker stack deploy and avoid managing a separate control plane. If a small backend team already runs PostgreSQL on a managed service like RDS, putting stateless APIs on a 3-node Swarm cluster delivers practical high availability without hiring a platform team.

Moving from Compose to Kubernetes is a shift in operating model, not just a deployment tool swap. Starting with a managed control plane (EKS, GKE, or AKS) removes etcd backup and control-plane upgrade pain, while running kind locally lets you test manifests, Gateway API routes, and probes before they hit production.

When not to use each orchestrator

Knowing when to rule a tool out prevents more outages than memorizing its features.

  • Don’t use Docker Compose when you cannot tolerate single-host downtime, vertical scaling has hit its ceiling, or you expect the orchestrator to auto-restart containers solely because a healthcheck turns unhealthy.
  • Don’t use Docker Swarm when you must run HA stateful databases with dynamic block storage inside the cluster, or when you need header/weighted L7 canary routing, namespace-scoped RBAC, and horizontal autoscaling (HPA). If your team already operates managed Kubernetes clusters, inserting Swarm as an intermediate step adds work without payoff.
  • Don’t use Kubernetes when one or two backend engineers run an MVP, internal admin tool, or homelab that fits comfortably on a single server. Maintaining a control plane, CNI, CSI driver, Gateway controller, and upgrade cadence will eat more time than shipping product code.

The two most expensive mistakes are self-hosting Kubernetes for a workload that fits on one VM, and running an RDBMS on Docker Swarm without placement constraints or an external database—only to watch a node drain spin up an empty volume on another host.

Summary and checklist

Pick the orchestrator that matches the operational complexity your team can actually sustain, not the one with the largest ecosystem. Run through these four checks before committing to a migration:

  1. Host count and downtime budget: If one machine and short restart windows are acceptable, staying on Docker Compose keeps delivery fast.
  2. State separation: Check whether your database can move to an external managed service first. Decoupling state makes Swarm far easier to operate safely.
  3. Traffic and lifecycle needs: Decide if start-first rolling updates are enough, or if you genuinely need Gateway API weighted canaries, separated startup/readiness/liveness probes, and preStop draining.
  4. Platform bandwidth: If you choose Kubernetes, budget for a managed control plane (EKS/GKE/AKS) and declarative GitOps rather than building a cluster from scratch.

References

Learn how to use Docker Compose to define and run multi-container applications with this detailed introduction to the tool.
Docker Engine Swarm mode overview
The Concepts section helps you learn about the parts of the Kubernetes system and the abstractions Kubernetes uses to represent your cluster, and helps you obtain a deeper understanding of how Kubernetes works.
This post is licensed under CC BY 4.0 by the author.