TExcelTAD
Home › Kubernetes › From Compose & Swarm to Kubernetes

From Compose & Swarm to Kubernetes

Many teams arrive at Kubernetes with an application that already runs under Docker Compose on one host or as a Docker Swarm stack. The good news: the concepts carry over, and a large part of the translation is mechanical. The less good news: a few Compose features have no Kubernetes equivalent, and a few Kubernetes concepts (probes, requests, PodDisruptionBudgets) don't exist in Compose, so a straight conversion is a starting point, not a finished job. This lesson maps the concepts, runs a small converter, and lists what you have to decide by hand. The Compose side of the story is in Compose to Kubernetes, the Swarm comparison in Swarm vs Kubernetes.

Concept map

Compose / Swarm Kubernetes Notes
service Deployment + Service A Service only if something connects to it
service with a named volume (a database) StatefulSet + PVC template Stable identity and storage per replica
deploy.mode: global DaemonSet One Pod per node
deploy.replicas spec.replicas Or an HPA
ports: "8080:80" Service port: 8080, targetPort: 80; Ingress/Gateway for HTTP Swarm's routing mesh ≈ NodePort/LoadBalancer
environment, env_file env, envFrom a ConfigMap
secrets Secret mounted as a volume Mount at /run/secrets to keep the app unchanged
configs ConfigMap mounted as a volume
named volumes PersistentVolumeClaim Size and StorageClass must be chosen
bind mounts (./src:/app) none (hostPath is not portable) Bake files into the image or use a ConfigMap
healthcheck liveness/readiness/startup probes Kubernetes separates "restart me" from "don't send traffic"
depends_on (+ condition: service_healthy) none Readiness probes, retries in the app, or an init container
deploy.resources.reservations / limits resources.requests / limits Requests drive scheduling
deploy.placement.constraints nodeSelector / node affinity
deploy.update_config strategy.rollingUpdate parallelism ≈ maxUnavailable
networks one flat Pod network; namespaces + NetworkPolicies Isolation is opt-in
profiles, build, container_name none Build in CI, push to a registry

Step 1: let Compose normalise the file

Compose files can use interpolation, .env files, anchors, extends and overrides. Don't convert the raw file: convert what Compose makes of it. docker compose config resolves everything into one canonical document:

compose · try it yourself
# $ docker compose config --no-path-resolution
services:
  web:
    image: nginx:1.29
    ports: ["8080:80"]
    depends_on: [api]
  api:
    image: ghcr.io/acme/shop-api:${API_TAG:-2.4.1}
    environment:
      DATABASE_HOST: db
      LOG_LEVEL: ${LOG_LEVEL:-info}
    secrets: [db_password]
    healthcheck:
      test: ["CMD", "wget", "-qO-", "http://localhost:9000/health"]
      interval: 10s
      timeout: 3s
      retries: 3
      start_period: 20s
    depends_on:
      db: {condition: service_healthy}
  db:
    image: postgres:17
    environment:
      POSTGRES_PASSWORD_FILE: /run/secrets/db_password
    secrets: [db_password]
    volumes: ["pgdata:/var/lib/postgresql/data"]
secrets:
  db_password:
    file: ./db_password.txt
volumes:
  pgdata:

# --- .env
API_TAG=2.5.0
name: demo
services:
  api:
    depends_on:
      db:
        condition: service_healthy
        required: true
    environment:
      DATABASE_HOST: db
      LOG_LEVEL: info
    healthcheck:
      test:
        - CMD
        - wget
        - -qO-
        - http://localhost:9000/health
      timeout: 3s
      interval: 10s
      retries: 3
      start_period: 20s
    image: ghcr.io/acme/shop-api:2.5.0
    networks:
      default: null
    secrets:
      - source: db_password
        target: /run/secrets/db_password
  db:
    environment:
      POSTGRES_PASSWORD_FILE: /run/secrets/db_password
    image: postgres:17
    networks:
      default: null
    secrets:
      - source: db_password
        target: /run/secrets/db_password
    volumes:
      - type: volume
        source: pgdata
        target: /var/lib/postgresql/data
        volume: {}
  web:
    depends_on:
      api:
        condition: service_started
        required: true
    image: nginx:1.29
    networks:
      default: null
    ports:
      - mode: ingress
        target: 80
        published: "8080"
        protocol: tcp
networks:
  default:
    name: demo_default
volumes:
  pgdata:
    name: demo_pgdata
secrets:
  db_password:
    name: demo_db_password
    file: ./db_password.txt

The tag came from .env, LOG_LEVEL fell back to its default, ports and depends_on became long syntax, and the implicit default network and the project-prefixed volume name (demo_pgdata) appeared. (--no-path-resolution keeps the secret's file path relative instead of turning it into an absolute path on this machine.) That normalised document (or --format json) is the right input for a converter.

Step 2: convert

Kompose is the established converter (kompose convert -f compose.yaml writes one file per object). The core of what it does fits in a short program. This one reads a normalised Compose model and emits Kubernetes objects, choosing a StatefulSet for services with named volumes and turning the healthcheck into probes:

python · try it yourself
import yaml

compose = yaml.safe_load("""
services:
  web: {image: "nginx:1.29", ports: [{target: 80, published: "8080"}]}
  api:
    image: ghcr.io/acme/shop-api:2.5.0
    environment: {DATABASE_HOST: db, LOG_LEVEL: info}
    secrets: [{source: db_password, target: /run/secrets/db_password}]
    expose: ["9000"]
    healthcheck: {test: [CMD, wget, -qO-, "http://localhost:9000/health"],
                  interval: 10s, timeout: 3s, retries: 3, start_period: 20s}
  db:
    image: postgres:17
    environment: {POSTGRES_PASSWORD_FILE: /run/secrets/db_password}
    secrets: [{source: db_password, target: /run/secrets/db_password}]
    volumes: [{type: volume, source: pgdata, target: /var/lib/postgresql/data}]
    expose: ["5432"]
""")

def secs(d):
    return int(d.rstrip("s"))

def k8s_name(n):
    return n.replace("_", "-")      # object names must be DNS-1123: no underscores

def container(name, svc):
    c = {"name": name, "image": svc["image"]}
    if svc.get("environment"):
        c["env"] = [{"name": k, "value": str(v)} for k, v in svc["environment"].items()]
    mounts = [{"name": k8s_name(s["source"]), "mountPath": s["target"], "subPath": s["source"], "readOnly": True}
              for s in svc.get("secrets", [])]
    mounts += [{"name": k8s_name(v["source"]), "mountPath": v["target"]} for v in svc.get("volumes", [])]
    if mounts:
        c["volumeMounts"] = mounts
    hc = svc.get("healthcheck")
    if hc:
        def probe():
            return {"exec": {"command": list(hc["test"][1:])}, "periodSeconds": secs(hc["interval"]),
                    "timeoutSeconds": secs(hc["timeout"]), "failureThreshold": hc["retries"]}
        c["readinessProbe"] = probe()
        c["livenessProbe"] = dict(probe(), initialDelaySeconds=secs(hc["start_period"]))
    return c

def convert(name, svc):
    stateful = any(v["type"] == "volume" for v in svc.get("volumes", []))
    pod = {"containers": [container(name, svc)]}
    if svc.get("secrets"):
        pod["volumes"] = [{"name": k8s_name(s["source"]), "secret": {"secretName": k8s_name(s["source"])}}
                          for s in svc["secrets"]]
    spec = {"replicas": 1, "selector": {"matchLabels": {"app": name}},
            "template": {"metadata": {"labels": {"app": name}}, "spec": pod}}
    if stateful:
        spec["serviceName"] = name
        spec["volumeClaimTemplates"] = [{"metadata": {"name": k8s_name(v["source"])},
            "spec": {"accessModes": ["ReadWriteOnce"], "resources": {"requests": {"storage": "10Gi"}}}}
            for v in svc["volumes"]]
    objs = [{"apiVersion": "apps/v1", "kind": "StatefulSet" if stateful else "Deployment",
             "metadata": {"name": name}, "spec": spec}]
    ports = [(int(p["published"]), p["target"]) for p in svc.get("ports", [])]
    ports += [(int(p), int(p)) for p in svc.get("expose", [])]
    if ports:
        objs.append({"apiVersion": "v1", "kind": "Service", "metadata": {"name": name},
                     "spec": {"selector": {"app": name},
                              "ports": [{"port": a, "targetPort": b} for a, b in ports]}})
    return objs

manifests = [o for name, svc in compose["services"].items() for o in convert(name, svc)]
print("generated:", ", ".join(f"{o['kind']}/{o['metadata']['name']}" for o in manifests))
print("---")
print(yaml.safe_dump(manifests[2], sort_keys=False), end="")
generated: Deployment/web, Service/web, Deployment/api, Service/api, StatefulSet/db, Service/db
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: api
spec:
  replicas: 1
  selector:
    matchLabels:
      app: api
  template:
    metadata:
      labels:
        app: api
    spec:
      containers:
      - name: api
        image: ghcr.io/acme/shop-api:2.5.0
        env:
        - name: DATABASE_HOST
          value: db
        - name: LOG_LEVEL
          value: info
        volumeMounts:
        - name: db-password
          mountPath: /run/secrets/db_password
          subPath: db_password
          readOnly: true
        readinessProbe:
          exec:
            command:
            - wget
            - -qO-
            - http://localhost:9000/health
          periodSeconds: 10
          timeoutSeconds: 3
          failureThreshold: 3
        livenessProbe:
          exec:
            command:
            - wget
            - -qO-
            - http://localhost:9000/health
          periodSeconds: 10
          timeoutSeconds: 3
          failureThreshold: 3
          initialDelaySeconds: 20
      volumes:
      - name: db-password
        secret:
          secretName: db-password

That api Deployment is valid and would run, and the app still finds its password at /run/secrets/db_password: the Secret's key db_password is mounted as a single file at that path with subPath (create it with kubectl create secret generic db-password --from-file=db_password=./db_password.txt; note that subPath mounts don't see later updates of the Secret). The converter had to rename db_password to db-password: Kubernetes object and volume names may not contain underscores. Notice what the converter could not know: how big the database volume should be (it guessed 10Gi), which CPU and memory requests to set, that web probably wants an Ingress or HTTPRoute instead of port 8080, and that the db_password Secret must be created from somewhere other than a local file. Kompose has the same gaps and lets you fill some of them with kompose.* labels in the Compose file.

From a Swarm stack: the deploy section

A Swarm stack carries more operational intent in deploy:, and most of it has a direct Kubernetes field. Here is a stack service as docker stack config sees it:

compose · try it yourself
# $ docker stack config -c stack.yaml
# --- stack.yaml
services:
  api:
    image: ghcr.io/acme/shop-api:2.5.0
    deploy:
      replicas: 4
      placement:
        constraints: [node.labels.zone == eu-1a, node.role == worker]
      resources:
        limits: {cpus: "0.50", memory: 512M}
        reservations: {cpus: "0.25", memory: 256M}
      update_config:
        parallelism: 1
        delay: 10s
        order: start-first
        failure_action: rollback
  node-exporter:
    image: prom/node-exporter:v1.9.1
    deploy:
      mode: global
version: "3.13"
services:
  api:
    deploy:
      replicas: 4
      update_config:
        parallelism: 1
        delay: 10s
        failure_action: rollback
        order: start-first
      resources:
        limits:
          cpus: "0.50"
          memory: "536870912"
        reservations:
          cpus: "0.25"
          memory: "268435456"
      placement:
        constraints:
          - node.labels.zone == eu-1a
          - node.role == worker
    image: ghcr.io/acme/shop-api:2.5.0
  node-exporter:
    deploy:
      mode: global
    image: prom/node-exporter:v1.9.1

And the mapping of those keys:

python · try it yourself
def cpu(v):
    m = round(float(v) * 1000)
    return f"{m}m" if m % 1000 else str(m // 1000)

def mem(v):
    units = {"K": "Ki", "M": "Mi", "G": "Gi"}
    return v[:-1] + units[v[-1].upper()]

def deploy_to_k8s(name, deploy):
    out, notes = {}, []
    if deploy.get("mode") == "global":
        out["kind"] = "DaemonSet"
    else:
        out["kind"] = "Deployment"
        out["replicas"] = deploy.get("replicas", 1)
    res = deploy.get("resources", {})
    if res:
        out["resources"] = {
            "requests": {"cpu": cpu(res["reservations"]["cpus"]), "memory": mem(res["reservations"]["memory"])},
            "limits": {"cpu": cpu(res["limits"]["cpus"]), "memory": mem(res["limits"]["memory"])}}
    selector = {}
    for c in deploy.get("placement", {}).get("constraints", []):
        key, value = [x.strip() for x in c.split("==")]
        if key.startswith("node.labels."):
            selector["topology.kubernetes.io/zone" if key.endswith(".zone") else key[12:]] = value
        elif key == "node.role" and value == "worker":
            notes.append("node.role == worker: default (control-plane nodes are tainted)")
    if selector:
        out["nodeSelector"] = selector
    uc = deploy.get("update_config")
    if uc:
        start_first = uc.get("order") == "start-first"
        out["strategy"] = {"maxSurge": uc["parallelism"] if start_first else 0,
                           "maxUnavailable": 0 if start_first else uc["parallelism"]}
        notes.append(f"delay {uc['delay']}: use minReadySeconds: {int(uc['delay'].rstrip('s'))}")
        if uc.get("failure_action") == "rollback":
            notes.append("failure_action rollback: no auto-rollback; use progressDeadlineSeconds + Argo Rollouts/Flagger")
    return out, notes

stack = {
    "api": {"replicas": 4,
            "placement": {"constraints": ["node.labels.zone == eu-1a", "node.role == worker"]},
            "resources": {"limits": {"cpus": "0.50", "memory": "512M"},
                          "reservations": {"cpus": "0.25", "memory": "256M"}},
            "update_config": {"parallelism": 1, "delay": "10s", "order": "start-first",
                              "failure_action": "rollback"}},
    "node-exporter": {"mode": "global"},
}
for name, deploy in stack.items():
    out, notes = deploy_to_k8s(name, deploy)
    print(f"{name}: {out}")
    for n in notes:
        print(f"  note: {n}")
api: {'kind': 'Deployment', 'replicas': 4, 'resources': {'requests': {'cpu': '250m', 'memory': '256Mi'}, 'limits': {'cpu': '500m', 'memory': '512Mi'}}, 'nodeSelector': {'topology.kubernetes.io/zone': 'eu-1a'}, 'strategy': {'maxSurge': 1, 'maxUnavailable': 0}}
  note: node.role == worker: default (control-plane nodes are tainted)
  note: delay 10s: use minReadySeconds: 10
  note: failure_action rollback: no auto-rollback; use progressDeadlineSeconds + Argo Rollouts/Flagger
node-exporter: {'kind': 'DaemonSet'}

Two translations need care. Swarm's 512M means mebibytes, as docker stack config shows by printing 536870912 bytes (512 × 1024²), so the Kubernetes value is 512Mi; in Kubernetes 512M would be 512,000,000 bytes, about 5% less. And Swarm's automatic rollback on a failed update has no built-in counterpart: a Deployment that stops progressing is marked ProgressDeadlineExceeded but stays where it is until you run kubectl rollout undo or a progressive-delivery tool does it for you.

What you have to decide by hand

  • Startup order. Kubernetes starts everything at once. Make apps retry their connections (they need that anyway, for restarts) and use readiness probes; an init container that waits for the database is the fallback.
  • Probes. One Compose healthcheck becomes up to three probes. Readiness should check "can I serve?", liveness only "am I stuck?"; using the same deep check for both turns a slow database into a restart storm.
  • Requests. Without resources.requests the scheduler packs Pods blindly (Requests, Limits & QoS).
  • Exposure. Published ports become a Gateway/HTTPRoute (or Ingress) for HTTP and a LoadBalancer Service for raw TCP.
  • Storage. Choose a StorageClass and size per volume, and plan how to move the data: dump and restore, or a replica that you promote.
  • Secrets. Files on a laptop don't belong in Git. Use an external secret store, Sealed Secrets or SOPS (GitOps).
  • Packaging. Put the cleaned-up manifests into Helm or Kustomize with one overlay per environment, so dev keeps its small settings and production gets replicas, budgets and policies.

A practical migration order: convert, clean up by hand, run the result in a local cluster, add probes, requests and a PodDisruptionBudget, then move one stateless service at a time while the database stays where it is.

Tip: Keep the Compose file for local development. Many teams use Compose (or Compose Watch) on laptops and Kubernetes in shared environments; both consume the same images, so the image, not the YAML, is the contract.

Learn more: Compose to Kubernetes · Swarm vs Kubernetes · Compose to Swarm · Docker Swarm stacks

Test yourself

Which Kubernetes object usually replaces a Compose database service with a named volume?

  1. A Deployment with emptyDir
  2. A StatefulSet with a volumeClaimTemplate
  3. A DaemonSet
  4. A ConfigMap

What is the Kubernetes counterpart of depends_on: {db: {condition: service_healthy}}?

  1. spec.dependsOn
  2. There is none; use readiness probes, retries in the app, or an init container
  3. A PodDisruptionBudget
  4. Service.spec.selector

A Swarm service has deploy.mode: global. What do you convert it to?

  1. A Deployment with replicas: 0
  2. A DaemonSet
  3. A Job
  4. A StatefulSet