Skip to content
Tutorials Center
My learning

Topics

Lesson 94 of 111 ยท Orchestration Basics

From Docker to Kubernetes

A Docker user's guide to Kubernetes: pods, deployments, services and config objects, how each maps to Docker and Compose concepts, and the kubectl basics.

Kubernetes (often written K8s) is the most widely used container orchestrator. It does the same job as Swarm from the previous lesson: keep the right number of containers running across many machines, replace the ones that fail, roll out new versions without downtime. But it does it with a larger, more flexible vocabulary and a huge ecosystem around it. The good news for you: Kubernetes runs the same OCI images you already build with Docker. Everything you learned about Dockerfiles, registries, healthchecks and environment variables carries over.

This lesson is a map, not a full course. You will see how Docker and Compose ideas translate into Kubernetes objects, how a small application is described, and which kubectl commands you will use first. It is not a substitute for a Kubernetes tutorial, and it deliberately skips cluster setup, networking plugins and operators.

There is no Kubernetes cluster on the machine used to write this track. Cluster commands and their output are read-only examples written from knowledge of how kubectl behaves. What was run for real is the part of kubectl that works offline: the client version and the --dry-run=client generators, whose YAML is shown exactly as printed.

The big picture

A Kubernetes cluster is a set of machines (nodes) managed by a control plane. You never talk to nodes directly. You send YAML descriptions of the state you want to the control plane's API server (kubectl is just a client for that API), and controllers inside the cluster work continuously to make reality match. This is the same "desired state versus actual state" idea as Swarm, taken further.

TEXT
   kubectl apply -f app.yaml
            |
            v
   +------------------ control plane ------------------+
   | API server <-> etcd (state)    scheduler           |
   |            controllers (deployments, nodes, ...)   |
   +--------------------+-------------------------------+
                        |  "run these pods on you"
        +---------------+----------------+
        v                                v
   +----------- node ----------+   +----------- node ----------+
   | kubelet + container       |   | kubelet + container       |
   | runtime (containerd)      |   | runtime (containerd)      |
   |  [pod] [pod]              |   |  [pod]                    |
   +---------------------------+   +---------------------------+

On each node, the kubelet talks to a container runtime. That runtime is usually containerd, the same component Docker uses under the hood (see How Docker Works). Modern Kubernetes does not need the Docker daemon at all, but the images are the same, and docker build output runs there unchanged.

Docker concepts and their Kubernetes cousins

In Docker or Compose In Kubernetes Notes
Container Container (inside a Pod) Same idea, but never created alone
docker run Pod The smallest unit: one or more containers sharing network and storage
Compose service with scale / Swarm service Deployment (manages a ReplicaSet of Pods) Declares replicas, update strategy, self-healing
Published port, service name DNS Service A stable virtual IP and DNS name in front of changing Pods
-p 80:80 from the internet Ingress (or Gateway) / Service of type LoadBalancer HTTP routing, TLS, cloud load balancers
environment:, env_file ConfigMap, Secret Settings outside the image
Named volume PersistentVolumeClaim A request for storage; the cluster supplies a volume
healthcheck: Probes: liveness, readiness, startup Readiness decides whether traffic is sent
deploy.resources / --memory resources.requests and resources.limits Requests are for scheduling, limits are caps
Compose project / Swarm stack Namespace plus a set of manifests (or a Helm chart) Namespaces group and isolate objects
Image tag in a registry Image tag in a registry Identical
restart: always Pod restartPolicy, plus the Deployment re-creating Pods
Global service on every node DaemonSet One Pod per node
docker run that runs once Job / CronJob Run to completion, optionally on a schedule
Database with a volume StatefulSet Stable names and storage per replica

The mental shift is that you rarely create Pods by hand. You create a Deployment, which creates a ReplicaSet, which creates Pods. If a Pod dies, the ReplicaSet makes another; if you change the image in the Deployment, it performs a rolling update.

Pods: why not just containers?

A Pod can hold several containers that must run together on one node, for example an application and a log-shipping sidecar. They share one network namespace (so they talk over localhost) and can share volumes. Most Pods have a single container, but the model matters because the Pod, not the container, is what Kubernetes schedules, restarts and gives an IP address to.

Pods are disposable. Each Pod gets its own IP, which changes whenever it is replaced. Never point other services at a Pod's IP; that is the job of a Service.

A small application, described

The Compose file of a minimal web service is about ten lines. The Kubernetes version is longer, because each concern gets its own object. This is a read-only example of a Deployment, a Service and a ConfigMap in one file (the three pieces are separated by ---):

YAML
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
spec:
  replicas: 3
  selector:
    matchLabels:
      app: web
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 0
  template:
    metadata:
      labels:
        app: web
    spec:
      containers:
        - name: nginx
          image: nginx:alpine
          ports:
            - containerPort: 80
          env:
            - name: LOG_LEVEL
              valueFrom:
                configMapKeyRef:
                  name: app-config
                  key: LOG_LEVEL
          resources:
            requests:
              cpu: 100m
              memory: 64Mi
            limits:
              cpu: 500m
              memory: 128Mi
          readinessProbe:
            httpGet:
              path: /
              port: 80
            periodSeconds: 10
---
apiVersion: v1
kind: Service
metadata:
  name: web
spec:
  selector:
    app: web
  ports:
    - port: 80
      targetPort: 80
  type: ClusterIP
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: app-config
data:
  LOG_LEVEL: info

Read it from top to bottom with Docker eyes:

  • replicas: 3 is the desired number of identical Pods.
  • selector.matchLabels and template.metadata.labels are the glue. A Deployment owns the Pods whose labels match its selector, and a Service finds its Pods the same way (selector: app: web). Labels, not names, connect objects in Kubernetes.
  • template is a Pod description. Its containers list is where your image goes.
  • maxSurge: 1, maxUnavailable: 0 means a rolling update first starts one extra Pod and only removes an old one after the new one is ready. It is the same idea as order: start-first in Swarm.
  • requests tell the scheduler how much CPU and memory to reserve on a node; limits are enforced by cgroups just like --memory and --cpus (Resource Limits). 100m means 100 millicores, one tenth of a CPU.
  • The readinessProbe is the cousin of HEALTHCHECK, but it has a precise job: a Pod that is not ready receives no Service traffic. A separate livenessProbe decides when to restart a container.
  • The Service gives web a stable cluster IP and DNS name. Other Pods in the same namespace call http://web, just as containers on a user-defined bridge call each other by name (Containers Talking to Each Other).

Writing manifests with generators

You do not have to type YAML from memory. kubectl create ... --dry-run=client -o yaml prints the manifest instead of sending it to a cluster, which is a quick way to start a file. These commands were run for real, because dry-run with client needs no cluster:

CONSOLE
$ kubectl create deployment web --image=nginx:alpine --replicas=3 --dry-run=client -o yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: web
  name: web
spec:
  replicas: 3
  selector:
    matchLabels:
      app: web
  strategy: {}
  template:
    metadata:
      labels:
        app: web
    spec:
      containers:
      - image: nginx:alpine
        name: nginx
        resources: {}
status: {}

The same trick builds the other objects:

CONSOLE
$ kubectl create service clusterip web --tcp=80:80 --dry-run=client -o yaml
apiVersion: v1
kind: Service
metadata:
  labels:
    app: web
  name: web
spec:
  ports:
  - name: 80-80
    port: 80
    protocol: TCP
    targetPort: 80
  selector:
    app: web
  type: ClusterIP
status:
  loadBalancer: {}

$ kubectl create configmap app-config --from-literal=LOG_LEVEL=info --dry-run=client -o yaml
apiVersion: v1
data:
  LOG_LEVEL: info
kind: ConfigMap
metadata:
  name: app-config

$ kubectl create job one --image=alpine:3 --dry-run=client -o yaml -- echo hi
apiVersion: batch/v1
kind: Job
metadata:
  name: one
spec:
  template:
    metadata: {}
    spec:
      containers:
      - command:
        - echo
        - hi
        image: alpine:3
        name: one
        resources: {}
      restartPolicy: Never
status: {}

Remove the status: {} and resources: {} noise, add what you need and commit the file to version control.

A Kubernetes Secret is only base64-encoded, not encrypted: kubectl create secret generic db --from-literal=password=x --dry-run=client -o yaml prints password: eA==, and anyone can decode that. Protect Secrets with RBAC and encryption at rest, or use an external secret manager. Never commit Secret manifests.

kubectl basics

kubectl reads its cluster address and credentials from a kubeconfig (by default ~/.kube/config), which can hold several clusters. A context selects one cluster, user and namespace, much like docker context selects a daemon. First check that the client is installed:

CONSOLE
$ kubectl version --client
Client Version: v1.36.1
Kustomize Version: v5.8.1

On a machine with no kubeconfig (like this one) the cluster commands fail, which is a useful error to recognize:

CONSOLE
$ kubectl get pods
E1023 19:16:47.583278    1764 memcache.go:265] "Unhandled Error" err="couldn't get current server API group list: the server could not find the requested resource"

Against a real cluster, a first session looks like this (read-only example, names and ages vary):

CONSOLE
$ kubectl apply -f app.yaml
deployment.apps/web created
service/web created
configmap/app-config created

$ kubectl get pods
NAME                   READY   STATUS    RESTARTS   AGE
web-6d8f9c7b5d-4kq2m   1/1     Running   0          35s
web-6d8f9c7b5d-9tz7p   1/1     Running   0          35s
web-6d8f9c7b5d-xw5lc   1/1     Running   0          35s

$ kubectl get deployment,service
NAME                  READY   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/web   3/3     3            3           35s

NAME          TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)   AGE
service/web   ClusterIP   10.96.41.20    <none>        80/TCP    35s

The commands you will use daily map neatly onto Docker ones:

Task Docker kubectl
List running things docker ps kubectl get pods
Inspect docker inspect web kubectl describe pod web-... or kubectl get pod web-... -o yaml
Logs docker logs -f web kubectl logs -f web-... (or deploy/web)
Shell in a container docker exec -it web sh kubectl exec -it web-... -- sh
Copy files docker cp kubectl cp
Reach a port locally -p 8080:80 kubectl port-forward svc/web 8080:80
Scale docker service scale kubectl scale deployment web --replicas=5
Update the image docker service update --image kubectl set image deployment/web nginx=nginx:1.29-alpine
Roll back docker service rollback kubectl rollout undo deployment/web
Watch a rollout docker service ps kubectl rollout status deployment/web
Delete docker rm -f kubectl delete -f app.yaml
Documentation of a field none kubectl explain pod.spec.containers.resources

When something is wrong, kubectl describe and its Events section tell you most of the story: image pull failures (ImagePullBackOff), unschedulable Pods (not enough CPU), crashing containers (CrashLoopBackOff; check kubectl logs --previous).

Use kubectl apply -f and keep the YAML in Git. Hand-editing live objects with kubectl edit creates drift that the next deploy silently overwrites. This is the same rule as "change the service, not the container" in Swarm.

Things that change when you move

  • Images must be in a registry the cluster can reach. Private registries need an image pull secret (Working with Registries).
  • Local development: Kubernetes in Docker Desktop, kind and minikube run a small cluster on your laptop. For daily app development, Compose is still simpler (Compose for Development).
  • Storage and state: Pods are disposable, so stateful workloads need PersistentVolumes and usually StatefulSets, or a managed database outside the cluster (Running Databases in Containers).
  • Healthchecks become probes and are mandatory in practice, because readiness drives load balancing and rollouts.
  • Logs and metrics are collected by cluster-level agents, not by looking at one host (Logging and Monitoring).
  • Security adds RBAC, network policies and Pod security settings on top of everything in Container Security Basics.
  • Convert with care. Tools such as Kompose translate a Compose file into manifests as a starting point, but the result still needs review: probes, resources and Secrets are yours to add.

When to choose Kubernetes

Choose it when you need many services across many nodes, autoscaling, strong ecosystem support (ingress controllers, certificate automation, operators for databases), or a managed offering from your cloud provider (EKS, GKE, AKS). Think twice when you have a handful of containers on one or two servers: the operational overhead is real, and Compose on a single host (Deploying on a Single Host) may serve you for years. The comparison for different team sizes is in Choosing Your Deployment Path.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the Kubernetes counterpart of a Compose service that you want to run with several replicas and rolling updates?

    A Deployment manages a ReplicaSet of identical Pods and performs rolling updates. A bare Pod has no replication or update strategy.
  2. 2. Why should other services not connect to a Pod's IP address?

    Pods are disposable and each replacement gets a new IP. A Service selects Pods by label and provides one stable virtual IP and name.
  3. 3. What does a readinessProbe control?

    A Pod that is not ready is removed from Service endpoints. A livenessProbe is the one that triggers a restart.
  4. 4. Which command prints a Deployment manifest without contacting any cluster?

    --dry-run=client builds the object locally and prints it. The other commands read from a cluster.
  5. 5. A Secret manifest contains password: eA==. What does that tell you?

    Base64 is an encoding, not encryption. Restrict access with RBAC, enable encryption at rest or use an external secret store.

Summary

  • Kubernetes runs the same OCI images as Docker. You declare the desired state in YAML; controllers keep reality in line with it.
  • Pods are the smallest unit (containers sharing network and storage); Deployments manage replicated Pods and rolling updates; Services give Pods a stable address; ConfigMaps and Secrets hold settings; PersistentVolumeClaims request storage.
  • Labels and selectors connect objects: Deployments find their Pods and Services find their endpoints this way.
  • Healthchecks become probes (readiness decides traffic, liveness decides restarts), and requests/limits replace --memory and --cpus.
  • kubectl create ... --dry-run=client -o yaml generates manifests offline; kubectl apply, get, describe, logs, exec, port-forward and rollout cover daily work.
  • Kubernetes brings a large ecosystem and more operational weight. For a few containers on one host, Compose is still enough.

Next: Logging and Monitoring