Docker & Kubernetes

Moving a Docker Compose App to Kubernetes, Service by Service

Docker Compose is a good fit for local development and single-host deployments. When an application needs to run on several machines, roll out without downtime, or recover from node failures on its own, teams usually move it to Kubernetes. There's no one-to-one translation between the two. Compose describes containers on one host, while Kubernetes describes a desired state that controllers keep enforcing across a cluster.

This guide translates a common Compose setup, a Node.js API backed by PostgreSQL, into Kubernetes manifests. It explains which Kubernetes object replaces each Compose feature and points out the places where a literal translation breaks.

How Compose Concepts Map to Kubernetes

At its heart, Docker Compose uses services to define and link containers. It manages container lifecycle, networking, and volumes primarily for a single-host environment. Kubernetes, on the other hand, operates on a cluster of machines and introduces a richer, more declarative API for managing applications at scale. Its core building blocks – Pods, Deployments, Services, ConfigMaps, Secrets, and Persistent Volume Claims – abstract away the underlying infrastructure and provide robust features like self-healing, scaling, and load balancing.

The challenge isn't just rewriting YAML; it's understanding how to express your application's requirements in Kubernetes' declarative language. We need to translate:

  • Services into Kubernetes Deployments (for managing Pods) and Services (for network access).
  • Environment variables into ConfigMaps and Secrets.
  • Volumes into Persistent Volume Claims and Persistent Volumes.
  • Network dependencies into Kubernetes' internal DNS-based service discovery.
  • depends_on into readiness probes plus application-level retries. Kubernetes has no startup ordering between Deployments.

Step 1: Deconstruct Your Docker Compose Application

First, let's establish our baseline. Here’s a typical docker-compose.yml for our example Node.js API with a PostgreSQL database. Pay close attention to the services, ports, environment variables, and volumes definitions.

YAML
# compose.yaml
services:
  web:
    build: .
    ports:
      - "3000:3000"
    environment:
      NODE_ENV: development
      DATABASE_URL: postgres://user:password@db:5432/mydatabase
    depends_on:
      - db
    volumes:
      - .:/app # For local development hot-reloading

  db:
    image: postgres:17
    environment:
      POSTGRES_DB: mydatabase
      POSTGRES_USER: user
      POSTGRES_PASSWORD: password
    volumes:
      - db_data:/var/lib/postgresql/data

volumes:
  db_data:

Two things in this file don't carry over to a cluster:

  • build: .: Kubernetes doesn't build images. Build a production image (typically with a multi-stage Dockerfile), tag it with a version, and push it to a registry your cluster can pull from.
  • The .:/app bind mount: this exists for hot reloading during development. In Kubernetes, the code ships inside the image.

Step 2: Externalize Configuration with ConfigMaps and Secrets

In Docker Compose, environment variables are specified directly within the service definition. In Kubernetes, for better manageability and security, we separate configuration from the deployment logic using ConfigMaps for non-sensitive data and Secrets for sensitive data.

Non-secret settings (NODE_ENV, the database host and port) go into a ConfigMap. Credentials go into Secrets. The API and the database get separate Secrets, because the official postgres image only reads variables named POSTGRES_USER, POSTGRES_PASSWORD and POSTGRES_DB.

YAML
# config.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: web-config
data:
  NODE_ENV: production
  DB_HOST: db          # the name of the database Service (Step 4)
  DB_PORT: "5432"      # ConfigMap values must be strings
---
apiVersion: v1
kind: Secret
metadata:
  name: db-credentials
type: Opaque
stringData:            # plain text here; Kubernetes stores it base64-encoded
  POSTGRES_DB: mydatabase
  POSTGRES_USER: app
  POSTGRES_PASSWORD: change-me

stringData takes plain values. If you use the data field instead, you have to base64-encode each value yourself.

⚠️ Common mistake: Treating base64 as encryption. Anyone who can read the Secret object can decode it, and unless the cluster has encryption at rest configured, it's stored readable in etcd. Don't commit real Secret manifests to Git. In production, create Secrets from a secret manager (for example with External Secrets Operator, or Sealed Secrets for a GitOps workflow).

Step 3: Translate Services to Kubernetes Deployments and Services

Each stateless Compose service becomes a Deployment plus a Service.

  • Deployment: Manages the desired state for your application's Pods (e.g., how many replicas, which Docker image). A Pod is the smallest deployable unit in Kubernetes, containing one or more containers.
  • Service: Defines a logical set of Pods and a policy by which to access them. This is how other parts of your application, or external users, discover and communicate with your application.

Node.js Web API

YAML
# web.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
spec:
  replicas: 2
  selector:
    matchLabels:
      app: web
  template:
    metadata:
      labels:
        app: web
    spec:
      containers:
        - name: web
          image: registry.example.com/web-app:1.0.0   # never :latest in a cluster
          ports:
            - containerPort: 3000
          envFrom:
            - configMapRef:
                name: web-config
          env:
            - name: DB_USER
              valueFrom:
                secretKeyRef: { name: db-credentials, key: POSTGRES_USER }
            - name: DB_PASSWORD
              valueFrom:
                secretKeyRef: { name: db-credentials, key: POSTGRES_PASSWORD }
            - name: DB_NAME
              valueFrom:
                secretKeyRef: { name: db-credentials, key: POSTGRES_DB }
          readinessProbe:            # only send traffic once the app answers
            httpGet: { path: /healthz, port: 3000 }
            periodSeconds: 5
          livenessProbe:             # restart the container if it hangs
            httpGet: { path: /healthz, port: 3000 }
            initialDelaySeconds: 15
          resources:
            requests: { cpu: 100m, memory: 128Mi }
            limits: { memory: 256Mi }
---
apiVersion: v1
kind: Service
metadata:
  name: web
spec:
  selector:
    app: web
  ports:
    - port: 80
      targetPort: 3000

The app builds its connection string from DB_HOST, DB_PORT, DB_USER, DB_PASSWORD and DB_NAME. Because there's no depends_on, the API may start before the database is ready. It should retry the connection instead of exiting, and its /healthz endpoint should fail until the connection works, so the readiness probe holds traffic back in the meantime.

This Service is ClusterIP (the default), so it's only reachable inside the cluster. To expose it publicly, put an Ingress or Gateway in front of it rather than giving every Service its own LoadBalancer.

PostgreSQL Database

Step 4: Run PostgreSQL with a StatefulSet and Persistent Storage

The named volume db_data becomes a PersistentVolumeClaim. For databases, use a StatefulSet rather than a Deployment. A StatefulSet gives each pod a stable name and its own volume, and during a rollout it won't start a second database pod against the same disk.

YAML
# db.yaml
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: db
spec:
  serviceName: db
  replicas: 1
  selector:
    matchLabels:
      app: db
  template:
    metadata:
      labels:
        app: db
    spec:
      containers:
        - name: postgres
          image: postgres:17
          ports:
            - containerPort: 5432
          envFrom:
            - secretRef:
                name: db-credentials     # POSTGRES_DB / USER / PASSWORD
          env:
            - name: PGDATA               # a subdirectory: many volumes contain lost+found
              value: /var/lib/postgresql/data/pgdata
          readinessProbe:
            exec:
              command: ["sh", "-c", "pg_isready -U \"$POSTGRES_USER\" -d \"$POSTGRES_DB\""]
            periodSeconds: 5
          volumeMounts:
            - name: data
              mountPath: /var/lib/postgresql/data
  volumeClaimTemplates:
    - metadata:
        name: data
      spec:
        accessModes: ["ReadWriteOnce"]
        resources:
          requests:
            storage: 5Gi
---
apiVersion: v1
kind: Service
metadata:
  name: db            # matches DB_HOST in the ConfigMap
spec:
  selector:
    app: db
  ports:
    - port: 5432

The claim uses the cluster's default StorageClass. Check which one that is with kubectl get storageclass, since its reclaim policy decides whether deleting the claim also deletes the data.

Running a single PostgreSQL pod like this is fine for staging. For production, consider a managed database (RDS, Cloud SQL, Azure Database) or an operator such as CloudNativePG, which handles replication, failover and backups.

Step 5: Deploy to Kubernetes

With all our YAML definitions in place, deploying to Kubernetes is straightforward using kubectl.

Bash
kubectl apply -f config.yaml -f db.yaml -f web.yaml

# Watch pods start; the web pods become Ready once they can reach the database
kubectl get pods -w

# Test the API from your machine without exposing it publicly
kubectl port-forward service/web 8080:80
curl http://localhost:8080/healthz

If a pod doesn't become Ready, kubectl describe pod <name> shows probe failures and scheduling problems, and kubectl logs <name> shows the application output.

💡 Tip: kompose convert -f compose.yaml produces a first draft of these manifests automatically. Treat its output as a starting point: it won't add probes, resource requests or a StatefulSet for the database. Once you deploy to more than one environment, manage the differences with Kustomize overlays or a Helm chart instead of copying YAML files.

Summary

  1. Ship images, not source: build, version and push an image for every service. build: and source bind mounts stay in Compose.
  2. Replace depends_on with probes and retries: apps should tolerate dependencies that aren't ready yet.
  3. Keep config and secrets separate, and remember that Secrets are only base64-encoded unless the cluster encrypts them.
  4. Treat stateful services differently: use a StatefulSet with a volume claim, or better, a managed database or an operator.
Advertisement