TExcelTAD
Home › Docker Swarm › Swarm vs Kubernetes

Swarm vs Kubernetes

You now know Swarm well enough to compare it fairly with Kubernetes, the orchestrator most job adverts mention. Both run containers across a cluster, keep a desired number of replicas alive, roll out updates and provide service discovery. They differ in scope, in how much they ask of you, and in what grows around them. Neither is "the right one" in general; this lesson helps you pick for a given team and workload.

Concept map

Idea Swarm Kubernetes
cluster brain managers (Raft built in) control plane: API server, scheduler, controllers, etcd (Raft)
unit you deploy service → tasks (one container each) Deployment → ReplicaSet → Pods (one or more containers)
one per node mode: global DaemonSet
run to completion replicated-job / global-job Job, CronJob
stable name + load balancing service VIP + embedded DNS Service (ClusterIP) + CoreDNS
headless / all endpoints endpoint_mode: dnsrr, tasks.<svc> headless Service
expose on every node routing mesh (ingress) NodePort Service
HTTP routing a proxy you deploy (Traefik, nginx) Ingress or Gateway API + controller
config files / secrets configs / secrets (immutable) ConfigMaps / Secrets (mutable)
storage that follows the workload volume plugins, CSI cluster volumes (limited) PersistentVolumeClaims, StorageClasses (mature)
placement constraints, spread preferences, max_replicas_per_node node selectors, affinity, taints/tolerations, topology spread
autoscaling none built in HorizontalPodAutoscaler, cluster autoscaler
access control none: Docker API access = admin RBAC, ServiceAccounts, admission control
network isolation separate overlay networks NetworkPolicies
packaging stack files (Compose format) YAML manifests, Helm, Kustomize
extensibility fixed feature set CRDs and operators

The same app in both

A stack service:

compose · try it yourself
# $ docker stack config -c stack.yaml
# --- stack.yaml
services:
  api:
    image: ghcr.io/acme/shop-api:2.4.1
    ports: ["8080:9000"]
    environment:
      LOG_LEVEL: info
    deploy:
      replicas: 3
      resources:
        limits: {cpus: "0.5", memory: 256M}
      update_config:
        parallelism: 1
        order: start-first
version: "3.13"
services:
  api:
    deploy:
      replicas: 3
      update_config:
        parallelism: 1
        order: start-first
      resources:
        limits:
          cpus: "0.5"
          memory: "268435456"
    environment:
      LOG_LEVEL: info
    image: ghcr.io/acme/shop-api:2.4.1
    ports:
      - mode: ingress
        target: 9000
        published: 8080
        protocol: tcp

The same in Kubernetes needs two objects, a Deployment and a Service, and more lines (see Deployments and Services):

yaml
apiVersion: apps/v1
kind: Deployment
metadata: {name: api}
spec:
  replicas: 3
  selector: {matchLabels: {app: api}}
  strategy:
    rollingUpdate: {maxUnavailable: 0, maxSurge: 1}
  template:
    metadata: {labels: {app: api}}
    spec:
      containers:
        - name: api
          image: ghcr.io/acme/shop-api:2.4.1
          env: [{name: LOG_LEVEL, value: info}]
          ports: [{containerPort: 9000}]
          resources:
            limits: {cpu: 500m, memory: 256Mi}
---
apiVersion: v1
kind: Service
metadata: {name: api}
spec:
  type: NodePort
  selector: {app: api}
  ports: [{port: 9000, targetPort: 9000, nodePort: 30080}]

Notice what's explicit in Kubernetes and implicit in Swarm: the labels that tie the Service to the Pods, the selector, the separate object for networking. That verbosity is the price of flexibility: in Kubernetes anything can select anything by label. Also: NodePorts must be in the 30000–32767 range by default, while Swarm publishes any port.

A rough translation model shows how the object count grows:

python · try it yourself
stack = {
    "web":    {"replicas": 3, "ports": ["80:8000"], "mode": "replicated"},
    "api":    {"replicas": 3, "ports": [], "mode": "replicated"},
    "db":     {"replicas": 1, "ports": [], "mode": "replicated", "volume": "pgdata"},
    "agent":  {"mode": "global", "ports": []},
}
configs, secrets = ["nginx_conf"], ["db_password"]

objects = []
for name, svc in stack.items():
    if svc["mode"] == "global":
        objects.append(("DaemonSet", name))
    elif "volume" in svc:
        objects.append(("StatefulSet", name))
        objects.append(("PersistentVolumeClaim (template)", svc["volume"]))
    else:
        objects.append(("Deployment", name))
    if svc["mode"] != "global":
        objects.append(("Service", name))
    if svc["ports"]:
        objects.append(("Ingress/HTTPRoute", name))
objects += [("ConfigMap", c) for c in configs] + [("Secret", s) for s in secrets]

print(f"stack: {len(stack)} services, {len(configs)} config, {len(secrets)} secret")
print(f"kubernetes: {len(objects)} objects")
for kind, name in objects:
    print(f"  {kind:<34} {name}")
stack: 4 services, 1 config, 1 secret
kubernetes: 11 objects
  Deployment                         web
  Service                            web
  Ingress/HTTPRoute                  web
  Deployment                         api
  Service                            api
  StatefulSet                        db
  PersistentVolumeClaim (template)   pgdata
  Service                            db
  DaemonSet                          agent
  ConfigMap                          nginx_conf
  Secret                             db_password

More objects isn't automatically worse: each one is small and does one thing, and tools like Helm and Kustomize manage them. But the learning curve and the daily operational surface are clearly bigger.

Where each one shines

Swarm is a good fit when:

  • the team already uses Compose and wants clustering with minimal new concepts;
  • the cluster is small to medium (a handful to a few dozen nodes) and the workloads are mostly stateless web services and workers;
  • you run on your own hardware or a few VMs and can't (or don't want to) run a Kubernetes control plane or pay for a managed one;
  • simplicity and low resource overhead matter more than ecosystem.

Kubernetes is a better fit when:

  • you need autoscaling, fine-grained access control for many teams, network policies or a rich storage story;
  • you want managed offerings (EKS, GKE, AKS) and the large ecosystem: operators for databases, service meshes, GitOps tools, policy engines;
  • you expect to hire people who already know it, or to run in several clouds;
  • the platform will host many unrelated applications.

A small helper that turns those points into a recommendation (adjust the weights to your situation):

python · try it yourself
def recommend(needs):
    k8s_only = [n for n in ("autoscaling", "rbac_multi_team", "network_policies", "operators", "managed_service")
                if needs.get(n)]
    swarm_points = sum([needs.get("team_knows_compose", False), needs.get("small_cluster", False),
                        needs.get("minimal_ops", False)])
    if len(k8s_only) >= 2:
        return "Kubernetes", "needs " + ", ".join(k8s_only)
    if swarm_points >= 2 and not k8s_only:
        return "Swarm", "simple needs, small cluster, little to operate"
    return "either", "prototype on Swarm, plan the path to Kubernetes" if k8s_only else "pick what the team knows"

for name, needs in {
    "agency hosting 5 client sites": dict(team_knows_compose=True, small_cluster=True, minimal_ops=True),
    "SaaS with 12 product teams":    dict(rbac_multi_team=True, autoscaling=True, managed_service=True),
    "startup, growing fast":         dict(team_knows_compose=True, small_cluster=True, autoscaling=True),
    "factory edge devices":          dict(small_cluster=True, minimal_ops=True),
}.items():
    choice, why = recommend(needs)
    print(f"{name:<30} -> {choice:<10} ({why})")
agency hosting 5 client sites  -> Swarm      (simple needs, small cluster, little to operate)
SaaS with 12 product teams     -> Kubernetes (needs autoscaling, rbac_multi_team, managed_service)
startup, growing fast          -> either     (prototype on Swarm, plan the path to Kubernetes)
factory edge devices           -> Swarm      (simple needs, small cluster, little to operate)

Migrating later

Choosing Swarm today doesn't lock you in. The images, the healthchecks, the twelve-factor configuration via environment variables and files, the stateless service design: all of that carries over. What changes is the deployment description. The From Compose & Swarm lesson walks through the translation, and Compose to Kubernetes covers tools like Kompose.

Learn more: Swarm Intro · Kubernetes Intro · Orchestration overview

Test yourself

What is the Kubernetes counterpart of a Swarm service in mode: global?

  1. Deployment
  2. StatefulSet
  3. DaemonSet
  4. Job

Which capability does Kubernetes have built in that Swarm lacks?

  1. Rolling updates
  2. Secrets
  3. Role-based access control (RBAC)
  4. Overlay networking

A Swarm endpoint_mode: dnsrr service corresponds most closely to which Kubernetes object?

  1. A NodePort Service
  2. A headless Service (clusterIP: None)
  3. An Ingress
  4. A LoadBalancer Service