All tutorials
  • #kubernetes
  • #k8s
  • #devops

Kubernetes 101: Running Containers at Scale

Clusters, nodes, pods, Deployments and Services in plain words, and what really happens when you run kubectl apply. Then run, scale, break and roll back an app on a local cluster.

Akshit Bansal20 min readTutorial 3

the manager for your containers
on this page

In one minute

Kubernetes
  • Kubernetes (K8s for short: K, then 8 letters, then s) runs containers across a group of machines.
  • You write down what you want ("3 copies of my web app"), and it keeps that true, forever.
  • If a container crashes or a machine dies, it starts a replacement by itself.
  • It does not build images. Docker (or a similar tool) builds them; Kubernetes runs them.

Words you need

  • Cluster

    A group of machines that Kubernetes manages as one big computer.

    Like a whole apartment society

  • Node

    One machine in the cluster, real or a VM. Your containers run on nodes.

    Like one building in the society

  • Control plane

    The brain of the cluster. It stores what you want and decides where things run. It does not run your app.

    Like the society office

  • Pod

    The smallest thing Kubernetes runs: a wrapper around one container (sometimes a few) with one IP address. Pods are disposable.

    Like one tenant; when they leave, a new one moves in

  • Replica

    One identical copy of a pod. Three replicas = three copies of your app sharing the work.

    Like three cashiers doing the same job

  • Deployment

    Your instruction 'keep N replicas of this pod running', plus safe updates to a new version.

    Like a standing order: always keep 3 flats rented

  • Service

    One fixed name and address in front of a changing group of pods. Callers use the Service, never a pod.

    Like the society's reception phone number

  • Desired state

    What you said you want, written down. Kubernetes keeps comparing reality to it and fixes differences.

    Like a thermostat set to 24°C

  • Manifest (YAML)

    A text file in YAML format that describes the desired state.

    Like the order form

  • kubectl

    The command-line tool you use to talk to a cluster. Say it 'kube-control' or 'kube-cuddle'; both are common.

    Like the phone to the society office

  • Label

    A key=value sticker on an object, like app=web. Services and Deployments find pods by their labels.

    Like a name tag at an event

  • Namespace

    A folder inside the cluster that groups objects, often one per team or environment.

    Like one wing of the building

Why Kubernetes exists

Docker runs containers on one machine. Real apps need more: many copies, many machines, and nobody awake at 3 a.m. to restart things.

JobBy hand with docker run + SSHWith Kubernetes
A server diesYou notice, SSH elsewhere, restart everythingPods are rescheduled on healthy nodes automatically
Traffic spikeStart more copies by hand, edit the load balancerChange a number, or let the autoscaler do it
New versionStop, pull, start on every server; downtimeRolling update, one pod at a time; rollback in one command
Where does it runA spreadsheet of IPsThe scheduler picks a node with room

What it gives you, from the official overview:

  • Self-healing

    Restarts crashed containers, replaces pods on dead nodes, and stops sending traffic to pods that fail their health checks.

  • Scaling

    Change one number to run more or fewer copies, or let an autoscaler do it from CPU usage.

  • Load balancing

    A Service gives pods one name and spreads requests across the healthy ones.

  • Rollouts and rollbacks

    Moves to a new version a few pods at a time, and back again with one command.

  • Bin packing

    You say how much CPU and memory each container needs; it fits them onto nodes efficiently.

  • Config and secrets

    Keeps settings and passwords outside your images, so one image works everywhere.

The cluster, piece by piece

Control plane (the brain)

API serverthe front door; kubectl talks to it
etcdthe memory: desired state
Schedulerpicks a node for each pod
Controllersfix differences, forever

Worker node 1

kubeletnode agent
kube-proxyService routing
containerdruntime
Podsweb, web

Worker node 2

kubeletnode agent
kube-proxyService routing
containerdruntime
Podsweb, redis
The control plane decides. Worker nodes do the work and report back.
ComponentIts jobLives on
kube-apiserverThe front door. Every command and every component talks to the cluster through itControl plane
etcdA small database holding the whole desired state of the clusterControl plane
kube-schedulerFinds pods with no node yet and picks a suitable node for eachControl plane
kube-controller-managerRuns the controllers: loops that fix differences between wanted and actualControl plane
kubeletThe node's agent: makes sure the pods assigned to this node are runningEvery node
kube-proxySets up network rules so Service addresses reach the right podsEvery node
Container runtimeActually runs containers, for example containerdEvery node

What happens when you run kubectl apply

  1. 01

    kubectl sends your YAML

    to the API server

  2. 02

    Saved in etcd

    this is now the desired state

  3. 03

    Deployment controller acts

    creates a ReplicaSet, which creates 3 pods

  4. 04

    Scheduler picks nodes

    each pod gets a node with room

  5. 05

    kubelet on that node starts it

    asks containerd to pull the image and run it

  6. 06

    Status reported back

    kubectl get pods shows Running

Desired state and the reconcile loop

You never say "start 3 pods". You say "there should be 3 pods", and controllers keep making it true.

You apply YAMLreplicas: 3
Controller compareswant 3, have 2
Actscreates 1 pod
Watches againforever
The loop never finishes. It runs as long as the cluster does.

Break it yourself: change replicas, delete pods, take nodes down, and read the log.

Control planein sync

wanted 3

running3/3

node-1Ready

  • web-1Running

node-2Ready

  • web-2Running

node-3Ready

  • web-3Running
  • clusterCluster ready: 3 pods wanted, 3 running.

A first manifest, explained

yaml
# Annotated example, not the walkthrough fileapiVersion: apps/v1kind: Deployment            # "keep N copies running"metadata:  name: webspec:  replicas: 3               # how many copies  selector:    matchLabels:      app: web              # manage pods with this label  template:                 # what each pod looks like    metadata:      labels:        app: web    spec:      containers:        - name: web          image: hits:1.0   # the image Docker built          ports:            - containerPort: 3000---apiVersion: v1kind: Service               # one stable name in front of the podsmetadata:  name: webspec:  selector:    app: web                # send traffic to pods labelled app=web  ports:    - port: 80              # the Service's port      targetPort: 3000      # the container's port

The objects that matter

ObjectWhat it isSociety analogy
PodSmallest unit: 1+ containers sharing an IP. Disposable, gets a new IP when replacedA tenant
DeploymentKeeps N identical pods running, does rolling updates and rollbacks"Always keep 3 flats rented"
ServiceOne stable name and IP in front of changing pods, picked by labelThe society's reception number
ConfigMap / SecretSettings / passwords outside the image. Secrets are only base64, not encryptedThe notice board / the locked drawer
NamespaceA folder for objects, per team or environmentA wing of the building
PVCA request for storage that outlives podsA storeroom you rent
HPAAdds or removes pods based on CPU (needs requests + metrics-server)More guards at festival time
Gateway APIRoutes outside HTTP traffic in. Replaces Ingress for new work (ingress-nginx retired March 2026)The main gate
Client podcalls http://web
Service: webstable name + IP, selector app=web

Pods labelled app=web

web-7d9f-x2k10.244.1.5
web-7d9f-q8p10.244.2.3
web-7d9f-m1z10.244.1.9 (new, replaced one)
Clients only know the Service. Pods behind it come and go.
Service typeReachable fromUse for
ClusterIP (default)Inside the cluster onlyService-to-service calls
NodePortA port on every nodeQuick tests, bare-metal setups
LoadBalancerA real cloud load balancerPublic traffic on a cloud (costs money)
Probe / settingQuestion it answersIf it fails
readinessProbeCan this pod take traffic now?Removed from the Service, keeps running
livenessProbeIs the process stuck?Container restarted
startupProbeHas a slow app finished booting?Others wait; restarted if it never boots
requestsHow much does it need? (scheduler uses this)Pod stays Pending if no node has room
limitsHard ceilingCPU throttled; memory: OOMKilled

Quick check: Your /health checks the database and you use it as the liveness probe. The database blips for 20 s. What happens?

More objects you will meet

  • Job / CronJob

    kind: CronJob

    Runs to completion: migrations, backups, reports. CronJob runs it on a schedule.

  • StatefulSet

    web-0, web-1, web-2

    Pods with stable names and their own volumes. For databases you cannot buy managed.

  • DaemonSet

    one per node

    One pod on every node: log shippers, monitoring agents, network plugins.

  • RBAC

    Role + RoleBinding

    Who may do which actions on which objects. Give apps the least they need.

  • NetworkPolicy

    podSelector + ingress

    A firewall between pods. By default every pod can reach every pod.

  • Helm / Kustomize

    helm install / kubectl apply -k

    Package and template YAML. Helm for third-party apps, Kustomize for per-environment patches.

Rolling, blue-green and canary

Built into every Deployment (maxSurge 1, maxUnavailable 0 here). What you do in the walkthrough.

Servicesends to every ready pod

v1 100%
  • v125%
  • v125%
  • v125%
  • v125%

v1 ready v2 ready starting% = share of requests

Step 1/6: Four v1 pods serve everything.

Reading pod status

Most problems show up first in the STATUS column of kubectl get pods. Pick one:

$ kubectl get pods

NAMEREADYSTATUSRESTARTSAGE
web-7d4f90/1Pending03m
  1. Scheduled: stuck (wait)
  2. Image pulled: not reached
  3. Created: not reached
  4. Started: not reached
  5. Ready: not reached

The pod requests 2 CPU. Free CPU on each node:

  • node-1 0.5
  • node-2 1.2
  • node-3 0.8

Pending

Accepted, but no node has agreed to run it yet.

Usual causes

  • No node has enough free CPU or memory for its requests
  • A PVC it needs is not bound
  • Taints, node selectors or affinity rule out every node
kubectl describe pod POD   # read Events at the bottomkubectl get nodeskubectl describe nodes | grep -A5 Allocated

kubectl cheat sheet

CommandWhat it does
kubectl get pods (-o wide)List pods (-o wide: with node and IP)
kubectl describe pod PODEverything about one pod; read Events at the bottom
kubectl logs POD (--previous)The app's output (--previous: from the last crash)
kubectl apply -f FILECreate or update objects from YAML
kubectl delete -f FILEDelete the objects in that YAML
kubectl exec -it POD -- shShell inside a pod's container
kubectl port-forward svc/web 8080:80Reach a Service from your laptop
kubectl scale deployment web --replicas=5Change the number of copies
kubectl rollout status / undo deployment/webWatch an update / go back to the previous version
kubectl get events --sort-by=.lastTimestampWhat just happened in the cluster

When not to use Kubernetes

  • One app or a few on one server: Compose is simpler.
  • Nobody on the team will own upgrades, access rules and monitoring.
  • A managed container service does the job: Cloud Run, AWS ECS/Fargate, Azure Container Apps.
  • Small, steady traffic: autoscaling buys you nothing.

Your Kubernetes roadmap

Topics from the roadmap.sh Kubernetes roadmap (opens in a new tab). Ticks stay in your browser.

Kubernetes roadmap

0/16

Learn now

Learn next

DIY walkthrough

You will run the hits app from Docker 101 on a real three-node cluster made with kind (Kubernetes in Docker), then scale it, kill pods, update it, break it and roll it back.

Before you start

You need the hits folder and the hits:1.0 image from the Docker 101 walkthrough, and Docker running. Check:

bash
docker image ls hits

You should see hits with tag 1.0. Run every command below from inside the hits folder.

Install kind and kubectl

powershell
winget install Kubernetes.kindwinget install -e --id Kubernetes.kubectl

Close and reopen PowerShell so the new commands are on your PATH.

  1. Check the tools and make a folder

    bash
    kind versionkubectl version --clientmkdir k8s

    You should see

    Both commands print a version, and an empty k8s folder now exists inside hits.

Build the cluster and deploy

kind (Kubernetes in Docker) builds a real cluster whose nodes are Docker containers. That is why it is perfect for a laptop, and why, on Windows and macOS, the whole cluster ends up as containers inside Docker Desktop's hidden VM.

hits/k8s/kind.yamlyaml
kind: ClusterapiVersion: kind.x-k8s.io/v1alpha4nodes:  - role: control-plane  - role: worker  - role: worker

The Redis file runs one Redis and gives it a Service named redis. It has no persistent volume, which is a deliberate shortcut and you will see its cost soon.

hits/k8s/redis.yamlyaml
apiVersion: apps/v1kind: Deploymentmetadata:  name: redisspec:  replicas: 1  selector:    matchLabels:      app: redis  template:    metadata:      labels:        app: redis    spec:      containers:        - name: redis          image: redis:7-alpine          ports:            - containerPort: 6379          resources:            requests:              cpu: 50m              memory: 32Mi            limits:              memory: 128Mi---apiVersion: v1kind: Servicemetadata:  name: redisspec:  selector:    app: redis  ports:    - port: 6379      targetPort: 6379

The web file has four things: a ConfigMap with the Redis address, a Deployment with three copies, probes and resource settings, and a Service that gives them one name. The rolling update settings mean "never remove a working pod before its replacement is ready".

hits/k8s/web.yamlyaml
apiVersion: v1kind: ConfigMapmetadata:  name: hits-configdata:  REDIS_URL: redis://redis:6379---apiVersion: apps/v1kind: Deploymentmetadata:  name: webspec:  replicas: 3  selector:    matchLabels:      app: web  strategy:    type: RollingUpdate    rollingUpdate:      maxSurge: 1      maxUnavailable: 0  template:    metadata:      labels:        app: web    spec:      containers:        - name: web          image: hits:1.0          imagePullPolicy: IfNotPresent          envFrom:            - configMapRef:                name: hits-config          ports:            - containerPort: 3000          readinessProbe:            httpGet:              path: /healthz              port: 3000            periodSeconds: 3          livenessProbe:            httpGet:              path: /healthz              port: 3000            initialDelaySeconds: 10            periodSeconds: 10          resources:            requests:              cpu: 50m              memory: 64Mi            limits:              memory: 128Mi---apiVersion: v1kind: Servicemetadata:  name: webspec:  selector:    app: web  ports:    - port: 80      targetPort: 3000
  1. Create the cluster

    The first run downloads a large node image, so be patient.

    bash
    kind create cluster --name hits --config k8s/kind.yamlkubectl get nodes

    You should see

    kind prints a few progress lines and ends with a message that you can now use your cluster. kubectl get nodes lists three nodes, all Ready (this can take a minute).
  2. Get your image into the cluster

    The cluster's nodes cannot see the images on your Docker. Normally they would pull from a registry. For a local image, load it into the nodes.

    bash
    kind load docker-image hits:1.0 --name hits

    You should see

    kind prints that it loaded the image onto each node.
  3. Apply the desired state

    bash
    kubectl apply -f k8s/redis.yaml -f k8s/web.yamlkubectl get pods --watch

    Press Ctrl+C once everything is Running, then:

    bash
    kubectl rollout status deployment/webkubectl get pods

    You should see

    After a short wait, rollout status says the deployment was successfully rolled out, and kubectl get pods shows three web pods and one redis pod, all Running and 1/1 Ready.
  4. Open a door to the Service

    port-forward is a temporary tunnel from your laptop to the Service. It is for debugging, not for production. Run it in one terminal and leave it running, and curl from another.

    bash
    kubectl port-forward service/web 8081:80
    bash
    curl http://localhost:8081

    Notice the "served by" name is always the same pod: the tunnel picked one pod when it started. To see the Service spreading load, ask from inside the cluster instead.

    bash
    kubectl exec deploy/web -- wget -T 5 -qO- http://webkubectl exec deploy/web -- wget -T 5 -qO- http://webkubectl exec deploy/web -- wget -T 5 -qO- http://web

    You should see

    The port-forward command stays running and prints Forwarding from 127.0.0.1:8081. In a second terminal the curl prints hits with a version of 1.0.
  5. Scale it

    bash
    kubectl scale deployment/web --replicas=5kubectl get podskubectl scale deployment/web --replicas=3

    You should see

    Five web pods are listed and become Ready within a few seconds. Scaling back to three terminates two.
  6. Kill a pod and watch it come back

    Pick any pod name from the list, replace POD_NAME with it, and delete it. This is the reconcile loop, live.

    bash
    kubectl get pods -l app=webkubectl delete pod POD_NAMEkubectl get pods -l app=web

    You should see

    The pod you deleted goes Terminating, and a new pod with a different suffix appears right away. The count stays at three.
  7. Feel the missing volume

    Redis here has no persistent storage, so its data lived and died with its pod. Real data needs a PVC (or a managed database).

    bash
    kubectl delete pod -l app=rediskubectl rollout status deployment/rediskubectl exec deploy/web -- wget -T 5 -qO- http://web

    You should see

    After the Redis pod is replaced, the counter starts again at 1. The pod's disk went with it.
  8. Roll out version 2.0

    Build a second image with a different version baked in, load it, and tell the Deployment to use it.

    bash
    docker build -t hits:2.0 --build-arg VERSION=2.0 .kind load docker-image hits:2.0 --name hitskubectl set image deployment/web web=hits:2.0kubectl rollout status deployment/webkubectl exec deploy/web -- wget -T 5 -qO- http://web

    If your port-forward from before dropped, that is normal: the pod it was attached to was replaced. Start it again if you want it.

    You should see

    Old pods are replaced gradually. rollout status ends with a success message. Calling the Service now prints version: 2.0.
  9. Break it on purpose

    Point the Deployment at a tag that does not exist. Because we set maxUnavailable: 0, Kubernetes refuses to remove a working pod until the new one is ready, so your app stays up.

    bash
    kubectl set image deployment/web web=hits:9.9kubectl get pods -l app=webkubectl get events --sort-by=.lastTimestamp

    Read the output top to bottom. Then ask for details of the broken pod (replace BAD_POD with its name). Look at the Events section at the bottom.

    bash
    kubectl describe pod BAD_POD

    You should see

    One new pod is stuck in ErrImagePull and then ImagePullBackOff, while the three version 2.0 pods keep serving traffic. The events end with a line like 'Back-off pulling image hits:9.9'.
  10. Roll back

    bash
    kubectl rollout undo deployment/webkubectl rollout status deployment/webkubectl exec deploy/web -- wget -T 5 -qO- http://web

    You should see

    rollout undo reports the rollback and rollout status ends with a success message. The broken pod disappears, and the Service answers with version: 2.0 again.

Clean up

Stop any port-forward terminal with Ctrl+C first.

  1. Delete the cluster

    bash
    kind delete cluster --name hitskind get clusters

    You should see

    kind get clusters prints no clusters.
  2. Delete the images

    The kind node image is large. List it, then remove it by the image ID in the first column. Then delete the hits folder.

    bash
    docker image rm hits:1.0 hits:2.0docker image ls kindest/node

    You should see

    docker images no longer lists hits.

Troubleshooting

Check the pod's status first: see Reading pod status.

Running on Kubernetes

kubectl exec ... wget times out straight after a rollout

Cause

A Service takes a moment to forget a pod that has just left, so one request can be sent to a pod that no longer exists. It clears by itself once the routing rules catch up. The -T 5 in our command is what stops this hanging for two minutes.

Fix

Run the same command again. If every attempt fails, check that the Service has healthy pods behind it.

bash
kubectl get endpointslices -l kubernetes.io/service-name=webkubectl get pods -l app=web
The connection to the server localhost:8080 was refused - did you specify the right host or port?

Cause

kubectl has no cluster to talk to. Either no cluster exists yet, it was deleted, Docker is stopped (kind nodes are containers), or kubectl points at the wrong context.

Fix

bash
docker pskind get clusterskubectl config get-contextskubectl config use-context kind-hits

If the cluster is missing, recreate it with the kind create cluster step.

web pod status: ErrImagePull, then ImagePullBackOff

Cause

The node tried to download the image and failed. In this tutorial that means the image was never loaded into kind, or the tag is misspelled. 'Back-off' means Kubernetes is waiting longer between tries.

Fix

Read the exact reason in the Events at the bottom of describe. Then fix the tag or load the image.

bash
kubectl describe pod POD_NAMEkind load docker-image hits:1.0 --name hits

If kind load itself errors, save the image to a file and load that instead.

bash
docker save hits:1.0 -o hits.tarkind load image-archive hits.tar --name hits
ErrImageNeverPull

Cause

The pod uses imagePullPolicy: Never, so Kubernetes will only use an image already on the node, and it is not there.

Fix

Load the image into the cluster, or switch the policy back to IfNotPresent in the YAML and apply again.

bash
kind load docker-image hits:1.0 --name hitskubectl apply -f k8s/web.yaml
CrashLoopBackOff

Cause

The container starts, exits and is restarted over and over, with growing waits. The cause is inside the app: a crash, a missing setting, or a failed connection.

Fix

Read the logs of the crashed attempt, not the new empty one.

bash
kubectl logs POD_NAME --previouskubectl describe pod POD_NAME
Pending, and the event says: 0/3 nodes are available: 3 Insufficient memory

Cause

The scheduler cannot find a node with enough free resources to satisfy the pod's requests. On a laptop this is often Docker's memory allowance being too small for three nodes.

Fix

Check what the event says exactly, then lower the requests in the YAML or give Docker more memory (Docker Desktop settings, Resources). Also look for a taint or label mismatch if the event says so.

bash
kubectl describe pod POD_NAMEkubectl describe nodes
Reason: OOMKilled, Exit Code: 137

Cause

The container used more memory than its limit, so the kernel killed it. Exit code 137 means it was killed by a signal.

Fix

Find it in describe, then raise the memory limit or fix the memory use.

bash
kubectl describe pod POD_NAME

Edit limits.memory in k8s/web.yaml and apply it again.

Readiness probe failed: HTTP probe failed with statuscode: 503

Cause

The app answered, but with an error, or it was not listening yet. For readiness this only removes the pod from the Service. For liveness, repeated failures restart the container.

Fix

Check the path, the port and the app's logs. The probe has to hit a URL that really exists.

bash
kubectl describe pod POD_NAMEkubectl logs POD_NAME

If the failure says connection refused during start-up, raise initialDelaySeconds or add a startup probe.

error: lost connection to pod

Cause

port-forward is attached to one specific pod. When that pod is replaced during a rollout, restart, or crash, the tunnel breaks.

Fix

Run the command again. It picks a pod that exists now.

bash
kubectl port-forward service/web 8081:80
bind: address already in use

Cause

An earlier port-forward is still running in another terminal, or another program uses that port.

Fix

Stop the old one with Ctrl+C, or choose another local port such as 8082:80.

A debug routine for any pod that is not running

Whatever the status says, work through the same five checks in order. Most problems show up in the first two.

  1. 01

    get pods

    What is the status?

  2. 02

    describe

    Read Events at the bottom

  3. 03

    logs

    What did the app say?

  4. 04

    logs --previous

    What did the last crash say?

  5. 05

    exec

    Look inside and test

bash
kubectl get podskubectl describe pod POD_NAMEkubectl logs POD_NAMEkubectl logs POD_NAME --previouskubectl exec -it POD_NAME -- sh

Next steps and sources