From Compose to Kubernetes
Kubernetes is where many Compose applications end up when they outgrow one host and the team wants the wider ecosystem: managed clusters from every cloud, autoscaling, Helm charts, GitOps. Unlike Swarm, Kubernetes doesn't read compose files. Every concept has a Kubernetes counterpart, though, and the translation is mechanical enough that a tool, Kompose, can produce a first draft.
This lesson maps the concepts, builds a small Kompose-style converter to show what a translation produces, and lists what you must still do by hand. The Kubernetes course picks it up from the cluster side in From Compose & Swarm.
The concept map
| Compose | Kubernetes | Notes |
|---|---|---|
| project | Namespace | one namespace per app/environment |
| service | Deployment (+ Pods) | StatefulSet for databases with stable storage |
deploy.replicas |
spec.replicas |
plus HorizontalPodAutoscaler for automatic scaling |
ports / service DNS name |
Service (ClusterIP) | the Service name is the DNS name, like in Compose |
| published port to the world | Ingress / Gateway + LoadBalancer | TLS lives here |
environment |
env, ConfigMap |
|
secrets / sensitive env |
Secret | mounted as files or env |
| named volume | PersistentVolumeClaim | storage comes from a StorageClass |
healthcheck |
livenessProbe / readinessProbe |
readiness gates traffic, which Compose can't do |
depends_on |
(nothing) | init containers or app-level retries |
deploy.resources |
resources.requests/limits |
reservations → requests |
restart |
restartPolicy (always Always in Deployments) |
|
profiles |
separate manifests / Helm values / Kustomize overlays |
Start from the rendered file
Kompose reads a compose file much like Compose does, so first make sure the file is what you think it is. The normalised form is also what any converter really works from: explicit ports, explicit volumes, explicit dependencies.
services:
web:
image: ghcr.io/acme/web:2.0
ports: ["8080:80"]
environment:
API_URL: http://api:5000
depends_on: [api]
deploy:
replicas: 2
api:
image: ghcr.io/acme/api:3.1
expose: ["5000"]
environment:
LOG_LEVEL: info
healthcheck:
test: ["CMD", "wget", "-qO-", "http://localhost:5000/health"]
interval: 10s
deploy:
resources:
limits: {memory: 256M}
reservations: {cpus: "0.25", memory: 128M}
db:
image: postgres:17
volumes: [pgdata:/var/lib/postgresql/data]
volumes:
pgdata:name: demo
services:
api:
deploy:
resources:
limits:
memory: "268435456"
reservations:
cpus: 0.25
memory: "134217728"
environment:
LOG_LEVEL: info
image: ghcr.io/acme/api:3.1
networks:
default: null
expose:
- "5000"
healthcheck:
test:
- CMD
- wget
- -qO-
- http://localhost:5000/health
interval: 10s
db:
image: postgres:17
networks:
default: null
volumes:
- type: volume
source: pgdata
target: /var/lib/postgresql/data
volume: {}
web:
deploy:
replicas: 2
environment:
API_URL: http://api:5000
image: ghcr.io/acme/web:2.0
networks:
default: null
depends_on:
api:
condition: service_started
required: true
ports:
- mode: ingress
target: 80
published: "8080"
protocol: tcp
networks:
default:
name: demo_default
volumes:
pgdata:
name: demo_pgdata
Note expose: ["5000"] on the API. Compose doesn't need it (containers on one network reach each other on any port), but a converter does: Kubernetes only creates a Service when it knows the port. Kompose likewise skips the Service for db, which declares no port at all. That's the first thing to fix in many conversions.
A Kompose-style converter
The model below reads a compose file and emits a Deployment per service, a Service for every service with a known port, and a PVC per named volume. It's simplified, but the output has the same shape as kompose convert:
import yaml
COMPOSE = """
services:
web:
image: ghcr.io/acme/web:2.0
ports: ["8080:80"]
environment: {API_URL: "http://api:5000"}
deploy: {replicas: 2}
api:
image: ghcr.io/acme/api:3.1
expose: ["5000"]
healthcheck:
test: ["CMD", "wget", "-qO-", "http://localhost:5000/health"]
interval: 10s
deploy:
resources:
limits: {memory: 256M}
reservations: {cpus: "0.25", memory: 128M}
db:
image: postgres:17
volumes: ["pgdata:/var/lib/postgresql/data"]
volumes:
pgdata: {}
"""
def mem(v): # Compose 256M -> Kubernetes 256Mi
return v[:-1] + "Mi" if v.endswith("M") else v
def convert(spec):
docs, warnings = [], []
for name, svc in spec["services"].items():
c = {"name": name, "image": svc["image"]}
ports = [int(p.split(":")[-1]) for p in svc.get("ports", [])] + [int(p) for p in svc.get("expose", [])]
if ports:
c["ports"] = [{"containerPort": p} for p in ports]
if svc.get("environment"):
c["env"] = [{"name": k, "value": str(v)} for k, v in svc["environment"].items()]
res = svc.get("deploy", {}).get("resources", {})
if res:
c["resources"] = {}
if "reservations" in res:
c["resources"]["requests"] = {k if k != "cpus" else "cpu": mem(v) if k == "memory" else v
for k, v in res["reservations"].items()}
if "limits" in res:
c["resources"]["limits"] = {k: mem(v) for k, v in res["limits"].items()}
hc = svc.get("healthcheck")
if hc:
c["livenessProbe"] = {"exec": {"command": hc["test"][1:]},
"periodSeconds": int(hc.get("interval", "30s").rstrip("s"))}
mounts, volumes = [], []
for v in svc.get("volumes", []):
vol, path = v.split(":")[:2]
mounts.append({"name": vol, "mountPath": path})
volumes.append({"name": vol, "persistentVolumeClaim": {"claimName": vol}})
if mounts:
c["volumeMounts"] = mounts
pod = {"containers": [c]}
if volumes:
pod["volumes"] = volumes
docs.append({"apiVersion": "apps/v1", "kind": "Deployment", "metadata": {"name": name},
"spec": {"replicas": svc.get("deploy", {}).get("replicas", 1),
"selector": {"matchLabels": {"app": name}},
"template": {"metadata": {"labels": {"app": name}}, "spec": pod}}})
if ports:
docs.append({"apiVersion": "v1", "kind": "Service", "metadata": {"name": name},
"spec": {"selector": {"app": name},
"ports": [{"port": int(p.split(":")[0]) if ":" in p else int(p),
"targetPort": int(p.split(":")[-1])}
for p in svc.get("ports", []) + svc.get("expose", [])]}})
else:
warnings.append(f"{name}: no ports or expose -> no Service, other pods can't reach it by name")
for vol in spec.get("volumes", {}):
docs.append({"apiVersion": "v1", "kind": "PersistentVolumeClaim", "metadata": {"name": vol},
"spec": {"accessModes": ["ReadWriteOnce"], "resources": {"requests": {"storage": "100Mi"}}}})
return docs, warnings
docs, warnings = convert(yaml.safe_load(COMPOSE))
for w in warnings:
print("WARN", w)
print("generated:", ", ".join(f"{d['kind']}/{d['metadata']['name']}" for d in docs))
print("---")
print(yaml.safe_dump(docs[2], sort_keys=False), end="")WARN db: no ports or expose -> no Service, other pods can't reach it by name
generated: Deployment/web, Service/web, Deployment/api, Service/api, Deployment/db, PersistentVolumeClaim/pgdata
---
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/api:3.1
ports:
- containerPort: 5000
resources:
requests:
cpu: '0.25'
memory: 128Mi
limits:
memory: 256Mi
livenessProbe:
exec:
command:
- wget
- -qO-
- http://localhost:5000/health
periodSeconds: 10
The printed Deployment for api shows the essential translations: replicas, the container port from expose, reservations turned into requests and 256M into 256Mi, and the healthcheck turned into an exec probe. The warning about db is real Kompose behaviour too.
Running Kompose
$ kompose convert -f compose.yaml -o k8s/
INFO Kubernetes file "k8s/api-service.yaml" created
INFO Kubernetes file "k8s/web-service.yaml" created
INFO Kubernetes file "k8s/api-deployment.yaml" created
INFO Kubernetes file "k8s/db-deployment.yaml" created
INFO Kubernetes file "k8s/pgdata-persistentvolumeclaim.yaml" created
INFO Kubernetes file "k8s/web-deployment.yaml" created
$ kubectl apply -f k8s/(sample output) Kompose understands a few labels to steer the result, for example kompose.service.type: LoadBalancer or kompose.service.expose: shop.example.com (creates an Ingress), and kompose.volume.size: 10Gi on volumes.
What to fix by hand
The generated YAML is a starting point, not a finished deployment:
- Readiness probes. Kompose maps a healthcheck to a liveness probe. You almost always want a
readinessProbe(HTTP) too, so traffic only reaches pods that are ready; see Probes. - Databases → StatefulSet, or better a managed database or an operator (StatefulSets, Operators).
- Secrets. Plain
environmentbecomes plainenv. Move passwords into Secrets and settings into ConfigMaps. - Ingress/Gateway with TLS instead of
ports: 8080:80: Ingress. - Startup order.
depends_ondisappears. Apps must retry connections; an init container can wait for the database if needed. - Storage sizes and classes: the default PVC size is tiny; choose a real size and StorageClass (Persistent Volumes).
- Packaging: turn the result into a Helm chart or Kustomize base + overlays (the counterpart of your override files): Helm, Kustomize.
Keeping Compose for development
Moving production to Kubernetes rarely means giving up Compose. A common split: developers keep compose.yaml + watch for the inner loop (fast, no cluster needed), CI runs integration tests with Compose, and the same images are deployed to Kubernetes with Helm. The image is the contract between both worlds; keep the environment variable names and ports identical, and the two configurations stay easy to compare.
Learn more: From Compose & Swarm · Kubernetes Deployments · Kubernetes Services · From Compose to Swarm
Test yourself
A compose service db has no ports or expose. What does Kompose generate for it?
- A Deployment and a Service on port 5432
- A Deployment but no Service, so other pods can't reach it by name
- Nothing
- A StatefulSet
What is the Kubernetes counterpart of a Compose named volume?
- ConfigMap
- emptyDir
- PersistentVolumeClaim
- Secret
What happens to depends_on when converting to Kubernetes?
- It becomes a readiness probe
- There is no equivalent: apps should retry, optionally with an init container that waits
- It becomes pod affinity
- Kubernetes starts pods in the listed order