Ravindra BagaleCourses & study guides मराठी

Chapter 67: Docker Swarm vs Kubernetes: the Same App on Both, Side by Side

67.4 Side by side: scaling, updates, self-healing, networking, storage, secrets and config compared

Why: the problem

We now have the same orders app running on a Swarm and on a Kubernetes cluster. This lesson puts the two next to each other, operation by operation, with the exact command for each tool and a measured result. The goal is an answer you can defend in an interview or an architecture review, built from what you ran, not from blog opinions. Why compare by operation? Because teams do not choose an orchestrator in the abstract; they choose it for the jobs they do every week. Those jobs are: deploy a new service, scale it up for a sale, ship a release safely, survive a node failure, connect services to each other, keep data, keep secrets, and see what is happening. If one tool does all of these well enough with less effort, it wins for that team. If the team needs autoscaling, policy and a large tool ecosystem, the other wins. What do we compare? Seven areas, each with a small runnable test on both clusters: scaling by hand and automatically, rolling update and rollback, self-healing after a node failure, service discovery and load balancing, persistent storage, secrets and config, and health checks. For each area you get a command table with the Swarm command on one side and the kubectl command on the other, and a verdict. How do we run it? Keep both clusters from 67.2 and 67.3 running, or recreate them with the scripts from those lessons. We use small shell functions sw and k so the commands line up: sw runs docker on the Swarm manager and k runs kubectl in the shop namespace. We fail a node on each side by stopping its container and time how long until all replicas run again, then test DNS names, mount secrets as files on both, and finally try autoscaling, which only one side can do natively. At the end you write the comparison table into a COMPARE.md file that you can attach to a design document.

What: every term in plain English

  • sw — Shell function: docker exec node1 docker, the Swarm manager CLI.
  • k — Shell function: kubectl -n shop.
  • Desired state — Both tools store it and reconcile; Raft in Swarm, etcd in Kubernetes.
  • Node failure detection — Swarm marks a node Down after missed heartbeats; Kubernetes waits for node-monitor-grace-period and taints.
  • Service discovery — Swarm: embedded DNS with a VIP; Kubernetes: CoreDNS with a ClusterIP.
  • Ingress load balancing — Swarm: routing mesh with IPVS; Kubernetes: kube-proxy with iptables, IPVS or nftables.
  • Volume driver — Swarm: local or plugin; Kubernetes: CSI with StorageClasses.
  • HPA — Kubernetes Horizontal Pod Autoscaler; Swarm has no native equivalent.
  • Config — Swarm config vs Kubernetes ConfigMap.
  • Ecosystem — Helm charts, operators, service meshes and managed offerings around a tool.
Define the sw and k helper functions. Scale both to ten and time it. Fail one node on each cluster. Measure recovery time. Resolve the database by DNS on both. Mount the secret as a file on both. Try autoscaling on both.
Seven areas compared on the same app

How: step by step

  1. Define the sw and k helper functions. Commands line up.
  2. Scale both to ten and time it. Similar speed.
  3. Fail one node on each cluster. Replicas rescheduled.
  4. Measure recovery time. Numbers recorded.
  5. Resolve the database by DNS on both. Names work.
  6. Mount the secret as a file on both. Same file path idea.
  7. Try autoscaling on both. Only Kubernetes has it built in.
  8. Compare health checks. Readiness has no Swarm twin.
  9. Write COMPARE.md. Table saved.

Read the table with care, because a few rows depend on settings rather than on the tool. Recovery time in Kubernetes moved from 342 seconds to about 60 after one patch, and could go lower with a shorter node-monitor-grace-period on the control plane. Secret protection in Kubernetes changes completely when you enable encryption at rest with AWS KMS on EKS, which most production clusters do. Swarm's rollout time depends almost entirely on the delay you choose. The rows that do not move with settings are the ones that matter most for a long-term choice: autoscaling, probe types, the extension API with custom resources and operators, and the availability of managed services from every big cloud. Those four rows are why the Cloud Native Computing Foundation's surveys show Kubernetes used by the large majority of organisations running containers in production.

Example 1: Scaling and node failure on both clusters

Goal. Scaling and node failure on both clusters.

fail.sh

sw() { docker exec node1 docker "$@"; }
k() { kubectl -n shop "$@"; }
sw service scale shop_orders=10 ; k scale deploy/orders --replicas=10
k rollout status deploy/orders
# Swarm: kill node2
docker stop node2 ; S=$(date +%s)
until [ "$(sw service ps shop_orders -f desired-state=running --format '{{.CurrentState}}' | grep -c Running)" = 10 ]; do sleep 1; done
echo "swarm recovered in $(( $(date +%s) - S ))s"
# Kubernetes: kill ch67-worker
docker stop ch67-worker ; S=$(date +%s)
until [ "$(k get pods -l app=orders --field-selector=status.phase=Running -o name | wc -l)" -ge 10 ] && \
      ! k get pods -o wide | grep -q 'ch67-worker '; do sleep 2; done
echo "k8s recovered in $(( $(date +%s) - S ))s"
docker start node2 ch67-worker

What each line does

  • Same replica count — Both clusters run ten replicas before the failure.
  • docker stop node2 — Stops a whole Swarm node, like a server losing power.
  • Swarm timer — Counts seconds until ten running tasks again.
  • Kubernetes timer — Waits until ten running pods exist and none are on the dead node.
  • Default timeouts — Kubernetes waits about 40 seconds to mark a node NotReady and 300 seconds before evicting pods, unless tolerations are shortened.

Green output

$ bash fail.sh
shop_orders scaled to 10
deployment.apps/orders scaled
deployment "orders" successfully rolled out
swarm recovered in 11s
k8s recovered in 342s

Expected result. With default settings Swarm reschedules much faster after a node failure. Kubernetes is deliberately patient, to avoid moving pods on a short network blip, and you tune it with tolerationSeconds on the pod; readiness still removes the dead pods from the Service at once, so traffic recovers well before 342 seconds.

Example 2: Tune Kubernetes eviction, then test DNS and secrets as files

Goal. Tune Kubernetes eviction, then test DNS and secrets as files.

tune.sh

k() { kubectl -n shop "$@"; }
sw() { docker exec node1 docker "$@"; }
k patch deploy orders --type=merge -p '{"spec":{"template":{"spec":{"tolerations":[
 {"key":"node.kubernetes.io/unreachable","operator":"Exists","effect":"NoExecute","tolerationSeconds":20},
 {"key":"node.kubernetes.io/not-ready","operator":"Exists","effect":"NoExecute","tolerationSeconds":20}]}}}}'
k rollout status deploy/orders
# DNS on both
T=$(sw ps -q --filter name=shop_orders | head -1)
sw exec $T getent hosts db
k exec deploy/orders -- getent hosts db.shop.svc.cluster.local
# secret as a file on both
k patch deploy orders --type=json -p '[
 {"op":"add","path":"/spec/template/spec/volumes","value":[{"name":"dbpw","secret":{"secretName":"db-password"}}]},
 {"op":"add","path":"/spec/template/spec/containers/0/volumeMounts","value":[{"name":"dbpw","mountPath":"/run/secrets","readOnly":true}]}]'
k rollout status deploy/orders
k exec deploy/orders -- ls /run/secrets
sw exec $T ls /run/secrets

What each line does

  • tolerationSeconds 20 — Pods leave an unreachable node after 20 seconds instead of 300.
  • getent hosts db — Swarm's embedded DNS returns the service VIP for db.
  • db.shop.svc.cluster.local — CoreDNS full name; the short name db also works in the same namespace.
  • Secret volume — Mounting at /run/secrets gives the app the same file path on both platforms.
  • readOnly — Secret files cannot be changed by the app.

Green output

$ bash tune.sh
deployment.apps/orders patched
deployment "orders" successfully rolled out
10.0.1.5        db
10.96.0.0       db.shop.svc.cluster.local   (headless: returns 10.244.2.7)
deployment.apps/orders patched
deployment "orders" successfully rolled out
password
db_password

Expected result. With 20 second tolerations Kubernetes recovered in about 60 seconds in our rerun. DNS-based discovery and secrets as files work the same way on both, so the application code does not care which orchestrator runs it.

Example 3: Autoscaling and the comparison table

Goal. Autoscaling and the comparison table.

compare.sh

k() { kubectl -n shop "$@"; }
k set resources deploy/orders --requests=cpu=50m
k autoscale deploy/orders --min=3 --max=12 --cpu-percent=60
k get hpa
docker exec node1 docker service update --help | grep -i autoscal || printf 'swarm: no autoscale option\n'
printf '%s\n' \
 '| Area | Docker Swarm | Kubernetes |' \
 '|---|---|---|' \
 '| Setup | swarm init + join, seconds | kind/kubeadm/EKS, minutes |' \
 '| Deploy file | one Compose stack | several YAML objects or Helm |' \
 '| Manual scale | docker service scale | kubectl scale |' \
 '| Autoscale | none built in | HPA, VPA, Karpenter |' \
 '| Rolling update | start-first, delay, auto rollback | maxSurge/maxUnavailable, manual undo |' \
 '| Node failure | about 10 s | 300 s default, tunable to about 60 s |' \
 '| Discovery | embedded DNS + VIP | CoreDNS + ClusterIP |' \
 '| Storage | local or plugin volumes | CSI, StorageClass, PVC |' \
 '| Secrets | encrypted in Raft, files | base64 in etcd, KMS encryption optional |' \
 '| Health | healthcheck only | liveness, readiness, startup |' \
 '| Managed cloud | none from AWS, GCP, Azure | EKS, GKE, AKS |' \
 '| Ecosystem | small | Helm, operators, meshes, GitOps |' > COMPARE.md
cat COMPARE.md

What each line does

  • kubectl autoscale — Creates an HPA that adds pods when CPU passes 60 percent (needs metrics-server from Chapter 63).
  • Swarm help grep — Shows there is no autoscale flag; you would script it yourself.
  • COMPARE.md — Markdown table built from your measurements, ready for a design document.
  • Health row — Swarm has one health check; Kubernetes separates liveness, readiness and startup.
  • Managed cloud row — The biggest practical factor for companies already on AWS.

Green output

$ bash compare.sh
deployment.apps/orders resource requirements updated
horizontalpodautoscaler.autoscaling/orders autoscaled
NAME     REFERENCE           TARGETS       MINPODS   MAXPODS   REPLICAS
orders   Deployment/orders   cpu: 4%/60%   3         12        10
swarm: no autoscale option
| Area | Docker Swarm | Kubernetes |
|---|---|---|
| Setup | swarm init + join, seconds | kind/kubeadm/EKS, minutes |
...
| Ecosystem | small | Helm, operators, meshes, GitOps |

Expected result. The HPA immediately plans to scale down from 10 to the minimum of 3 because CPU is low, something Swarm cannot do on its own. The table is your one-page answer to the comparison question.

Every command, step by step (kind lab with kubectl)

  1. Helpers

    sw() { docker exec node1 docker "$@"; }
    

    What it does: Swarm CLI.

    (no output)
    
  2. Scale

    sw service scale shop_orders=10
    

    What it does: Swarm.

    scaled to 10
    
  3. Scale

    kubectl -n shop scale deploy/orders --replicas=10
    

    What it does: K8s.

    scaled
    
  4. Fail

    docker stop node2
    

    What it does: Swarm node down.

    node2
    
  5. Fail

    docker stop ch67-worker
    

    What it does: K8s node down.

    ch67-worker
    
  6. Nodes

    kubectl get nodes
    

    What it does: NotReady.

    ch67-worker NotReady
    
  7. Tolerate

    kubectl -n shop patch deploy orders ... tolerationSeconds 20
    

    What it does: Faster eviction.

    patched
    
  8. DNS

    kubectl -n shop exec deploy/orders -- getent hosts db
    

    What it does: Discovery.

    10.244.2.7 db
    
  9. HPA

    kubectl -n shop autoscale deploy/orders --min=3 --max=12 --cpu-percent=60
    

    What it does: Autoscale.

    autoscaled
    
  10. Table

    cat COMPARE.md
    

    What it does: Result.

    | Area | Docker Swarm | Kubernetes |
    

When it is red 1

HPA TARGETS cpu: unknown/60%

Cause. metrics-server missing or no CPU request.

Fix, step by step

  1. Install metrics-server; set requests.

When it is red 2

pods stay Terminating on a stopped node

Cause. Kubelet unreachable, pods cannot confirm shutdown.

Fix, step by step

  1. Normal; they clear when the node returns or is deleted.

When it is red 3

getent: not found

Cause. Minimal image without getent.

Fix, step by step

  1. Use nslookup from a busybox debug pod.

When it is red 4

Swarm tasks pile up on the remaining nodes after recovery

Cause. Swarm does not rebalance when a node returns.

Fix, step by step

  1. docker service update --force shop_orders.

When it is red 5

The Deployment is invalid: spec.template.spec.volumes

Cause. JSON patch path wrong.

Fix, step by step

  1. Use add when the list does not exist yet.

Practice tasks

Easy Task 1: Helpers

Why: Define.

What to do: Write sw and k.

How:
  1. Functions.
Solution
type sw k

Easy Task 2: Scale

Why: Ten.

What to do: Scale both to ten.

How:
  1. Time it.
Solution
kubectl -n shop get deploy

Easy Task 3: DNS

Why: Names.

What to do: Resolve db on both.

How:
  1. getent.
Solution
kubectl -n shop exec deploy/orders -- getent hosts db

Medium Task 4: Fail

Why: Node.

What to do: Stop one node on each.

How:
  1. Timer.
Solution
docker ps

Medium Task 5: Tune

Why: Tolerations.

What to do: Add 20 s tolerations.

How:
  1. Rerun.
Solution
kubectl -n shop get deploy orders -o yaml

Medium Task 6: Secret

Why: File.

What to do: Mount the Secret at /run/secrets.

How:
  1. ls.
Solution
kubectl -n shop exec deploy/orders -- ls /run/secrets

Hard Task 7: HPA

Why: Autoscale.

What to do: Create the HPA.

How:
  1. metrics-server.
Solution
kubectl -n shop get hpa

Hard Task 8: Meesho

Why: Main task.

What to do: COMPARE.md with your numbers.

How:
  1. Every row.
Solution
cat COMPARE.md

Homework: try at home

For Meesho's catalogue service, run both clusters with ten replicas, fail one node on each, tune Kubernetes tolerations, rerun, and produce COMPARE.md with your own timings for scale, rollout, recovery and autoscaling.

Recap

  • Both tools scale, update, heal and discover services; the details differ.
  • Swarm reschedules after node failure faster by default; Kubernetes is tunable.
  • Secrets as files and DNS names keep app code identical on both.
  • Only Kubernetes has built-in autoscaling and multiple probe types.
  • Managed services and ecosystem decide most real-world choices.

FAQ

Q. Why is Kubernetes so slow to evict by default?

To avoid moving hundreds of pods during a short network split. Five minutes is a safe default for big clusters; latency-sensitive apps lower it per pod.

Q. Does Swarm have a readiness concept?

Partly. During updates it waits for the healthcheck, and unhealthy tasks are replaced, but there is no separate state that removes a running task from load balancing while keeping it alive.

Q. Which uses less memory?

Swarm. A manager adds tens of megabytes to the Docker Engine, while a Kubernetes control plane needs about 2 GB. On small edge devices this matters, which is why lightweight distributions like K3s exist.

Q. Is K3s a middle ground?

Yes. K3s is a certified Kubernetes in one small binary, popular for edge and IoT, with Swarm-like simplicity and the full Kubernetes API.

Interview questions

  1. Compare self-healing in Swarm and Kubernetes.

    Model answer: Both reconcile desired replicas; Swarm reschedules after node loss in seconds, Kubernetes after tolerationSeconds, 300 by default.

  2. How does load balancing differ?

    Model answer: Swarm uses a VIP and the IPVS routing mesh; Kubernetes uses ClusterIP with kube-proxy or eBPF, plus Ingress and Gateway API for L7.

  3. What does Kubernetes offer that Swarm does not?

    Model answer: HPA, VPA, CRDs and operators, RBAC, NetworkPolicy, admission control, CSI and managed services.

  4. When is Swarm good enough?

    Model answer: Small teams, a handful of services, on-premise or edge, little need for autoscaling or a large ecosystem.

Quick quiz

Q1. Which tool recovers faster with defaults?

Swarm.

Q2. Which setting speeds Kubernetes eviction?

tolerationSeconds.

Q3. Which tool has a built-in autoscaler?

Kubernetes.

Q4. How do apps find the database on both?

DNS name db.

Q5. Does Swarm rebalance after a node returns?

No, use update --force.

Samajla ka?