Platform Engineering · Lesson 07

Containers and a Local Kubernetes Cluster: Docker or Podman, kind, and kubectl

Containers and Kubernetes are where most later labs run, and both can run entirely on your laptop at no cost. A container engine (Docker or Podman) runs containers; kind ("Kubernetes in Docker") runs a whole Kubernetes cluster inside containers; kubectl talks to it. This lesson sets all three up, runs a first container with limits, creates a named cluster, deploys to it, and deletes it again. It also shows the two mistakes that matter most: sending a command to the wrong cluster because of the current context, and a second cluster that will not start.

Difficulty: Beginner · Know this first: Lesson 06, Lesson F25

What you will learn

By the end of this lesson you can work at four levels:

This page teaches it with a plain-language analogy, an animated diagram with normal and failure scenarios, a simulator, a quiz, basic, intermediate, advanced, and master checks, the expert detail ("Go deeper"), a production incident, a hands-on lab with commands and their output, and a production design exercise.

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

This bar adds up minutes from a working shell to a deployment on a local cluster, cleaned up. It is a worked example, not a measurement; downloads depend on your connection. The create and context hops decide whether the cluster starts and whether commands reach the right one.

Try it: does your command reach the cluster you meant?

Pick how you target the cluster, whether another cluster is running, and the host's inotify limit.

startsnew cluster
labcommands reach
22minutes

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

Local containers and clusters grow in four levels: running containers, running a cluster, working safely with several clusters, and making local environments disposable.

Basic — Run containers

At the basic level you can run and remove containers.

  • docker version with a server; hello-world.
  • docker run with --rm, -d, --name, -p, and pinned tags.
  • docker ps, logs, and rm -f by name.

Where it breaks: unnamed containers piling up, and :latest changing under you.

Try it: Basic

docker run says "Cannot connect to the Docker daemon". What is wrong?

Now do it: Stop and start the engine and watch docker version.

Intermediate — Run a cluster

At the intermediate level you have a cluster on your laptop.

  • kind create cluster --name, and kind delete cluster.
  • kubectl get, create, rollout status, and logs.
  • Resource limits on containers.

Try it: Intermediate

Where does kind put the cluster's credentials?

Now do it: List your contexts.

Advanced — Several clusters, safely

At the advanced level you never act on the wrong cluster.

  • --context on every changing command, or a prompt that shows the context.
  • Separate kubeconfig files (KUBECONFIG) for practice and work.
  • Known host limits (inotify, memory, disk) for running several clusters.

Try it: Advanced

What is the safest place for production cluster credentials?

Now do it: Remove contexts you do not need.

Master — Disposable environments

At the master level clusters are created from code and thrown away.

  • kind cluster configs in the repository (nodes, ports, versions).
  • A script that creates the cluster, installs add-ons, and verifies them.
  • The same setup used in CI for integration tests.

Trade-off: a local cluster is free and fast to rebuild and is not production: one node, no cloud load balancers, different storage. Test those differences somewhere real before you rely on them.

Try it: Master

Your CI uses kind for integration tests. What does it not tell you about production?

Now do it: List them for one service.

Go deeper

Installing pinned kind and kubectl on Linux x86-64 (replace the versions with current ones from the projects' release pages; use arm64 for ARM machines):

KIND=v0.29.0; KUBECTL=v1.33.1
curl -fsSLo kind "https://kind.sigs.k8s.io/dl/$KIND/kind-linux-amd64"
curl -fsSLo kubectl "https://dl.k8s.io/release/$KUBECTL/bin/linux/amd64/kubectl"
chmod +x kind kubectl && sudo mv kind kubectl /usr/local/bin/
kind version && kubectl version --client

kind can pin the Kubernetes version of the cluster too, with --image kindest/node:vX.Y.Z; each kind release lists the node images it was tested with. A cluster config file adds worker nodes and port mappings:

kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
nodes:
  - role: control-plane
    extraPortMappings:
      - containerPort: 30080      # a NodePort service inside the cluster
        hostPort: 8080            # reachable as localhost:8080
  - role: worker

Known issue, for several clusters on one host: sudo sysctl -w fs.inotify.max_user_instances=512 and fs.inotify.max_user_watches=524288; put them in /etc/sysctl.d/ to keep them after a restart. Minikube and k3d are alternatives to kind with the same idea.

One time it broke

This is a composite of a failure pattern that keeps repeating; the details are illustrative. The practice cleanup that was not.

Timeline

  • TuesdayA new engineer gets credentials for the team's shared development cluster for a demo; kubectl switches to it.
  • Wednesday 10:12Working through a tutorial on a local cluster, they run its cleanup: kubectl delete namespace demo. The local cluster had failed to start earlier, so the command goes to the shared cluster, which also has a namespace called demo.
  • 10:20Teammates report their demo environment gone. It is recreated from manifests and a database backup by 10:57.

What changed after

Shared-cluster credentials are issued per session and expire; tutorials in the team guide use --context everywhere; deleting a namespace in the shared cluster needs a separate role; and shell prompts show the current context.

Try it yourself, from scratch

Everything here runs on any Linux machine: your own laptop, WSL on Windows (run wsl --install in PowerShell once), or a small cloud VM. The Python needs only Python 3 and its standard library; check that you have it with python3 --version.

Before you start: Docker (Engine on Linux and WSL, or Docker Desktop) or Podman, plus kind and kubectl (install commands are in "Go deeper"), about 4 GB of free memory, and Python 3. The lab creates its own cluster named onboarding-lab and deletes it at the end; other clusters are not touched.

1. Linux commands

Type each one, read what it prints, and compare it with the note above it.

  1. Check that both the Docker client and the engine answer, then run the smallest possible container.

    Reversible

    docker version --format 'client {{.Client.Version}}, server {{.Server.Version}}'
    docker run --rm hello-world | sed -n 2p

    Options: --format picks fields with a Go template; --rm removes the container when it exits; sed -n 2p prints only line 2.

    Expect: client 29.x, server 29.x (your versions), then Hello from Docker!.

    If it fails: "Cannot connect to the Docker daemon": start the engine (sudo systemctl start docker, or open Docker Desktop). "permission denied … docker.sock": add yourself to the docker group on your own machine (sudo usermod -aG docker $USER, then log out and in), knowing it is equivalent to root.

  2. Run nginx in the background with a port, a memory limit, and a CPU limit; check it, then remove it by name.

    Reversible

    docker run -d --name onboarding-web -p 8089:80 --memory 128m --cpus 0.5 nginx:1.27-alpine
    sleep 2; curl -sI http://localhost:8089 | head -1
    docker inspect onboarding-web --format 'memory={{.HostConfig.Memory}} nanocpus={{.HostConfig.NanoCpus}}'
    docker rm -f onboarding-web

    Options: -d detached; --name a name to manage it by; -p 8089:80 your port 8089 to the container's 80; --memory and --cpus limits; a pinned tag instead of latest.

    Expect: A long container ID (and image download lines the first time), HTTP/1.1 200 OK, memory=134217728 nanocpus=500000000 (128 MiB, half a CPU), and the name onboarding-web as it is removed.

    If it fails: "port is already allocated": another program uses 8089; choose another port, such as -p 8090:80.

  3. Create a named local cluster. kind adds a context called kind-onboarding-lab and switches to it; note your previous context first so you can switch back.

    Reversible

    kubectl config current-context 2>/dev/null || echo "(no current context)"
    kind create cluster --name onboarding-lab --wait 180s
    kind get clusters

    Options: --name names the cluster (and its context, kind-onboarding-lab); --wait waits for the control plane to be ready.

    Expect: Your previous context (or none), then kind's progress lines and a closing line ("Have a nice day!" or "Thanks for using kind!", depending on the version) after about a minute, and onboarding-lab in the list.

    If it fails: If it fails at "Starting control-plane" while another cluster is running, raise the host's inotify limit (sudo sysctl -w fs.inotify.max_user_instances=512), delete the half-made cluster (kind delete cluster --name onboarding-lab), and create it again. A failed create also leaves your previous context current: do not run the next step until kind get clusters lists onboarding-lab.

  4. Deploy two nginx pods, naming the context on every command so nothing can reach another cluster.

    Reversible

    Changes a real system: On any machine with more than one cluster, name the context on every command that changes something; the current context is just whatever was used last.

    CTX=kind-onboarding-lab
    kubectl --context $CTX get nodes
    kubectl --context $CTX create deployment hello --image=nginx:1.27-alpine --replicas=2
    kubectl --context $CTX rollout status deployment/hello --timeout=120s
    kubectl --context $CTX get pods -l app=hello

    Options: --context chooses the cluster for this one command; create deployment makes a Deployment; rollout status waits until it is ready; -l app=hello selects its pods by label.

    Expect: onboarding-lab-control-plane Ready, deployment.apps/hello created, "successfully rolled out", and two hello-… pods 1/1 Running.

  5. Delete the cluster and check what is left.

    Potentially destructive

    kind delete cluster --name onboarding-lab
    kind get clusters
    kubectl config current-context 2>/dev/null || echo "(no current context: switch back with kubectl config use-context NAME)"
    docker system df

    Expect: Deleting cluster "onboarding-lab" ...; the list no longer has it (it may be empty, or show your other clusters). With other clusters, there is no current context until you switch back to yours by name. docker system df shows the disk used by images, including the node image and nginx, which you can remove with docker image rm if you need the space.

2. Python: context_guard.py

This program is a guard that a script can run before any kubectl command that changes something: it reads a kubeconfig, finds the current context, and refuses unless the context is the one the script expected and is not marked as production, the check that would have stopped the wrong-cluster accident in this lesson. Save it as context_guard.py, then run it.

# context_guard.py
KUBECONFIG = {
    "current-context": "team-dev-shared",
    "contexts": [
        {"name": "kind-onboarding-lab", "cluster": "kind-onboarding-lab"},
        {"name": "team-dev-shared", "cluster": "dev-eu-1"},
        {"name": "prod-eu-1", "cluster": "prod-eu-1"},
    ],
}
PROTECTED = ("prod",)                                   # name fragments that must never be the target

def guard(expected, action, context=None):
    target = context or KUBECONFIG["current-context"]
    names = [c["name"] for c in KUBECONFIG["contexts"]]
    if target not in names:
        return f"REFUSE {action}: context {target} does not exist"
    if any(p in target for p in PROTECTED):
        return f"REFUSE {action}: {target} is a protected context"
    if target != expected:
        return f"REFUSE {action}: would run against {target}, expected {expected}; pass --context {expected}"
    return f"ok     {action} on {target}"

print(guard("kind-onboarding-lab", "kubectl delete namespace demo"))
print(guard("kind-onboarding-lab", "kubectl delete namespace demo", context="kind-onboarding-lab"))
print(guard("prod-eu-1", "kubectl scale deploy/api --replicas=0", context="prod-eu-1"))
print(guard("kind-onboarding-lab", "kubectl apply -f app.yaml", context="kind-onboardinglab"))

Run it, and you should see this output:

$ python3 context_guard.py
REFUSE kubectl delete namespace demo: would run against team-dev-shared, expected kind-onboarding-lab; pass --context kind-onboarding-lab
ok     kubectl delete namespace demo on kind-onboarding-lab
REFUSE kubectl scale deploy/api --replicas=0: prod-eu-1 is a protected context
REFUSE kubectl apply -f app.yaml: context kind-onboardinglab does not exist

3. What to notice

4. Advanced: every step as one Bash script

The same Linux steps, made into a real script you can keep and run again. It uses the Bash features a production script needs: functions (one per step), an array of step names, arguments to choose steps, a case for options, exit codes recorded for each step, and a trap that prints a summary even when you stop it with Ctrl+C. Make a folder for this lesson (mkdir -p ~/labs/containers-and-local-kubernetes-docker-podman-kind-and-kubectl && cd ~/labs/containers-and-local-kubernetes-docker-podman-kind-and-kubectl) and save this as lab.sh.

#!/usr/bin/env bash
# The Linux steps of "Containers and a Local Kubernetes Cluster: Docker or Podman, kind, and kubectl", as one script (save it as lab.sh).
#
#   ./lab.sh          run every step, in order
#   ./lab.sh 2 4      run only steps 2 and 4
#   ./lab.sh --list   list the steps
#
# The steps share one shell, so a later step can use what an earlier one set up (a folder,
# a variable, a container): run them all in order the first time. Your own scripts should
# start with "set -euo pipefail"; this one runs teaching commands, and some of them fail on
# purpose, so it records each step's exit code instead of stopping at the first failure.

STEPS=(
  'Check that both the Docker client and the engine answer, then run the smallest possible container.'
  'Run nginx in the background with a port, a memory limit, and a CPU limit; check it, then remove it by name.'
  'Create a named local cluster. kind adds a context called kind-onboarding-lab and switches to it; note your previous context first so you can switch back.'
  'Deploy two nginx pods, naming the context on every command so nothing can reach another cluster.'
  'Delete the cluster and check what is left.'
)

step_1() {
docker version --format 'client {{.Client.Version}}, server {{.Server.Version}}'
docker run --rm hello-world | sed -n 2p
}

step_2() {
docker run -d --name onboarding-web -p 8089:80 --memory 128m --cpus 0.5 nginx:1.27-alpine
sleep 2; curl -sI http://localhost:8089 | head -1
docker inspect onboarding-web --format 'memory={{.HostConfig.Memory}} nanocpus={{.HostConfig.NanoCpus}}'
docker rm -f onboarding-web
}

step_3() {
kubectl config current-context 2>/dev/null || echo "(no current context)"
kind create cluster --name onboarding-lab --wait 180s
kind get clusters
}

step_4() {
CTX=kind-onboarding-lab
kubectl --context $CTX get nodes
kubectl --context $CTX create deployment hello --image=nginx:1.27-alpine --replicas=2
kubectl --context $CTX rollout status deployment/hello --timeout=120s
kubectl --context $CTX get pods -l app=hello
}

step_5() {
kind delete cluster --name onboarding-lab
kind get clusters
kubectl config current-context 2>/dev/null || echo "(no current context: switch back with kubectl config use-context NAME)"
docker system df
}

# print a step that has to be run by hand, instead of running it
by_hand() {
  echo "  (run this one yourself: $1)"
  sed 's/^/    /'
}

RESULTS=()
run_step() {
  local n=$1 start=$SECONDS code
  printf '\n== step %d of %d: %s\n' "$n" "${#STEPS[@]}" "${STEPS[n-1]}"
  "step_$n"
  code=$?
  RESULTS+=("step $n: exit code $code, $((SECONDS - start)) s")
}

summary() {
  echo
  echo "== summary"
  local r
  for r in "${RESULTS[@]}"; do echo "  $r"; done
}

case "${1:-}" in
  -h|--help) sed -n '2,6p' "$0"; exit 0 ;;
  --list) for i in "${!STEPS[@]}"; do echo "$((i + 1)). ${STEPS[i]}"; done; exit 0 ;;
esac

[ $# -eq 0 ] && set -- $(seq 1 "${#STEPS[@]}")
for n in "$@"; do
  if ! [[ $n =~ ^[0-9]+$ ]] || (( n < 1 || n > ${#STEPS[@]} )); then
    echo "there is no step '$n'; try --list" >&2
    exit 2
  fi
done
trap summary EXIT
trap 'echo; echo "stopped with Ctrl+C"; exit 130' INT
for n in "$@"; do run_step "$n"; done

Then make it executable and run it:

chmod +x lab.sh
./lab.sh --list     # the steps
./lab.sh            # every step, then a summary of exit codes and times
./lab.sh 2 3        # only steps 2 and 3

5. Learn the basics behind it

New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.

If you remember nothing else

Design exercise

Your team wants every engineer to run the platform locally on kind for development and to run the same setup in CI. Design it.

Clarifying questions to ask

Which engine and versions? How is the cluster defined and created? How are images built and loaded? How do engineers avoid acting on shared clusters by mistake? What host settings are needed? How is it reset?

Rough sizing

Say 15 engineers on Windows (WSL), macOS, and Linux, laptops with 16 GB of memory, and 8 services.

Shape of the answer

Docker Engine in WSL and Linux, Docker Desktop or Podman Desktop on macOS; pinned kind and kubectl installed by a script; a kind config in the repository; a make target that creates the cluster, loads locally built images (kind load docker-image), installs add-ons, and verifies them; --context everywhere in scripts; a separate KUBECONFIG for shared clusters with short-lived credentials; documented inotify settings; make reset deletes the cluster by name.

Trade-offs to name

A full local platform needs a lot of memory; trimming it to the services a person works on is faster but tests less.

Failure modes and how to troubleshoot them

Each row is one way this system went wrong in the diagram's scenarios. The hop number is where to look first.

ScenarioWhereEffectWhat goes wrong
Wrong contextHop 7: ContextBreaksThe cluster create failed earlier and was retried later, so the current context was still the team's shared development cluster, added yesterday for a demo. The lab commands do not name a context.
Wrong contextHop 8: DeployBreaksThe deployment lands in the shared cluster, and the lab's cleanup, "kubectl delete namespace demo", deletes the team's demo namespace there, with its database and secrets. Restoring it from manifests and a backup takes 45 minutes.
Second cluster will not startHop 6: Create clusterBreakskind stops at "Starting control-plane": kubeadm init fails because the API server never answers. With another cluster running, the host has used up its 128 inotify instances.

How to troubleshoot

  1. Write down the symptom and when it started: what users see, which number moved, and what changed just before (a deploy, a config change, traffic).
  2. Walk the path in order, from the first hop to the last: Engine → Permissions → First container → Limits and ports → kind and kubectl → Create cluster → Context → Deploy → Reset. The first hop whose evidence is wrong is where to dig.
  3. At that hop, run the read-only check from the diagram or the lab first; change nothing until the evidence points at a cause.
  4. Fix the smallest thing that restores service, or roll back the last change, and confirm the symptom is gone with the same check.
  5. Write down what you found and the check that would have caught it sooner, so the next person starts there.

References and review

The official documentation and standards behind this lesson. Versions and defaults change; when a command or field here differs from them, trust the official page.

Last updated . Next review due by November 2027. Found something out of date? Tell me.

Saved on this device, in this browser.
Next in this series · Lesson 08
Safe Commands: Read-Only, Reversible, Destructive, and Privileged — Previews, Backups, and Cleanup

Every command belongs to one of four classes. Read-only commands only look. Reversible ones change something you can undo. Potentially destructive ones delete or overwrite.

Go to Lesson 08 →

Or browse the full course from the Lessons index.