Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Lab · 40 min · revision 3

Lab: deploy, configure and expose a service with honest probes, requests and limits

On a local kind cluster, deploy a small HTTP service with a ConfigMap, a Deployment with requests, limits and three probes, a ClusterIP Service and a Gateway API HTTPRoute, then break readiness and liveness on purpose and watch what each one does.

Contentsand lesson path

What you will learn

  • Deploy a stateless service with a Deployment, Service, Gateway API route or Ingress, ConfigMap, resource requests and limits, and readiness and liveness probes.

Prerequisites: Containerization

01. Goal and setup

You will run a stateless service the way most teams do: configuration in a ConfigMap, Pods managed by a Deployment with resource requests, limits and probes, a Service for a stable in-cluster name, and a Gateway API HTTPRoute to reach it from outside the cluster. Then you will make one replica unready and another one unhealthy, and compare the results.

You need: Docker, kind v0.33.0, kubectl v1.36 or v1.37 (within one minor version of the cluster), curl, Python 3.10 or later for step 2, and about 3 GB of free disk. Tested versions: node image kindest/node:v1.37.0, python:3.13-alpine, busybox:1.37, and Envoy Gateway v1.9.4, which ships Gateway API v1.6.1. Commands assume bash.

Outputs from the cluster below are illustrative: Pod names, ages and addresses differ on your machine. The output of step 2 comes from a real run.

Project layout at the end of the lab
k8s-lab/
├── app.py      step 2: the service (Python standard library only)
├── web.yaml    step 3: ConfigMap, Deployment and Service
└── route.yaml  step 5: GatewayClass, Gateway and HTTPRoute

02. Step 1: Create a cluster

kind runs a whole Kubernetes node inside one Docker container. Pin the node image so your cluster matches the lesson.

Terminal
kind create cluster --name k8s-lab --image kindest/node:v1.37.0
kubectl get nodes
Illustrative output
NAME                    STATUS   ROLES           AGE   VERSION
k8s-lab-control-plane   Ready    control-plane   40s   v1.37.0

03. Step 2: Write the service and try it locally

The service uses only the Python standard library, so a stock python image can run it. It has two health endpoints that answer different questions. /healthz asks "is this process still able to work?" and fails only if the file /tmp/wedged exists. /ready asks "should this replica get traffic right now?" and fails while /tmp/drain exists. Those files are switches for step 6. It reads GREETING and APP_VERSION from the environment, and stops cleanly on SIGTERM, the signal the kubelet sends before it stops a container.

Python · app.py
"""web: a tiny HTTP service for the Kubernetes labs (Python stdlib only)."""
import os
import signal
import socket
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

PORT = int(os.environ.get("PORT", "8080"))
GREETING = os.environ.get("GREETING", "hello")
VERSION = os.environ.get("APP_VERSION", "dev")


class Handler(BaseHTTPRequestHandler):
    def do_GET(self) -> None:
        if self.path == "/healthz":  # liveness: can this process still serve?
            code = 500 if os.path.exists("/tmp/wedged") else 200
        elif self.path == "/ready":  # readiness: send traffic here now?
            code = 503 if os.path.exists("/tmp/drain") else 200
        elif self.path == "/work":  # burn about 20 ms of CPU per request
            end = time.process_time() + 0.02
            while time.process_time() < end:
                pass
            code = 200
        else:
            code = 200 if self.path == "/" else 404
        text = f"{GREETING} from {socket.gethostname()} ({VERSION})"
        if self.path != "/":
            text = {200: "ok", 404: "not found", 500: "wedged", 503: "draining"}[code]
        body = text.encode() + b"\n"
        self.send_response(code)
        self.send_header("Content-Type", "text/plain")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def log_message(self, *args) -> None:  # one line per request is too noisy
        pass


server = ThreadingHTTPServer(("", PORT), Handler)
stop = lambda *_: threading.Thread(target=server.shutdown).start()  # noqa: E731
signal.signal(signal.SIGTERM, stop)
print(f"web {VERSION} listening on :{PORT}", flush=True)
server.serve_forever()
print("SIGTERM received, stopped cleanly", flush=True)
Terminal · try it before you deploy it
rm -f /tmp/drain /tmp/wedged
GREETING=hi python3 app.py &
until curl -s -o /dev/null localhost:8080/healthz; do sleep 0.2; done  # wait for it
curl -s localhost:8080/
curl -si localhost:8080/ready | head -1
touch /tmp/drain
curl -si localhost:8080/ready | head -1
rm /tmp/drain
kill %1; wait
Expected output (your host name instead)
web dev listening on :8080
hi from daopc-OptiPlex-9010 (dev)
HTTP/1.0 200 OK
HTTP/1.0 503 Service Unavailable
SIGTERM received, stopped cleanly

04. Step 3: Deploy it with probes, requests and limits

Save the manifest below as web.yaml. Read it with these points in mind.

  • ConfigMap. web-config holds settings; envFrom turns each key into an environment variable. Environment variables are read when the container starts, so changing the ConfigMap later does not change running Pods. A second ConfigMap, web-code, created from app.py, is mounted as files under /app.
  • Requests are what the scheduler reserves on a node; it places Pods by requests, not by live usage. Limits are enforced at run time: a container that uses more memory than its limit is OOM-killed, while CPU above a CPU limit is only throttled. Here memory request equals memory limit, so the node never overcommits this memory. There is no CPU limit, so the service may use idle CPU; many teams make that choice to avoid throttling, while others set one for predictability.
  • QoS class. A Pod is Guaranteed only if every container sets CPU and memory requests equal to limits. This Pod is Burstable. Under node memory pressure, the kubelet evicts Pods whose usage exceeds their requests first; Guaranteed Pods are evicted last but are not immune, and a container over its own memory limit is OOM-killed, not evicted.
  • Probes. The startupProbe gives the app up to 60 seconds (30 × 2 s) to start and holds back the other probes until it passes. The readinessProbe decides traffic: after 3 failures in a row the Pod is marked not ready and the EndpointSlice controller marks its endpoint not ready, but the container keeps running. The livenessProbe decides restarts: after 3 failures the kubelet kills and restarts the container.
YAML · web.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: web-config
data:
  GREETING: hello
  APP_VERSION: v1
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
spec:
  replicas: 3
  selector:
    matchLabels:
      app: web
  template:
    metadata:
      labels:
        app: web
    spec:
      containers:
        - name: app
          image: docker.io/library/python:3.13-alpine
          command: ["python", "/app/app.py"]
          ports:
            - containerPort: 8080
          envFrom:
            - configMapRef:
                name: web-config
          volumeMounts:
            - name: code
              mountPath: /app
          resources:
            requests: {cpu: 50m, memory: 64Mi}
            limits: {memory: 64Mi}
          startupProbe:
            httpGet: {path: /healthz, port: 8080}
            periodSeconds: 2
            failureThreshold: 30
          readinessProbe:
            httpGet: {path: /ready, port: 8080}
            periodSeconds: 5
            failureThreshold: 3
          livenessProbe:
            httpGet: {path: /healthz, port: 8080}
            periodSeconds: 10
            failureThreshold: 3
      volumes:
        - name: code
          configMap:
            name: web-code
---
apiVersion: v1
kind: Service
metadata:
  name: web
spec:
  selector:
    app: web
  ports:
    - port: 80
      targetPort: 8080
Terminal
kubectl create configmap web-code --from-file=app.py
kubectl apply -f web.yaml
kubectl rollout status deployment/web --timeout=120s
kubectl get pods -l app=web
Illustrative output
configmap/web-code created
configmap/web-config created
deployment.apps/web created
service/web created
Waiting for deployment "web" rollout to finish: 0 of 3 updated replicas are available...
Waiting for deployment "web" rollout to finish: 1 of 3 updated replicas are available...
Waiting for deployment "web" rollout to finish: 2 of 3 updated replicas are available...
deployment "web" successfully rolled out
NAME                   READY   STATUS    RESTARTS   AGE
web-7d4b9c6f8d-2fj9q   1/1     Running   0          31s
web-7d4b9c6f8d-8xq4n   1/1     Running   0          31s
web-7d4b9c6f8d-tz6lw   1/1     Running   0          31s

05. Step 4: Call the Service and read its endpoints

From a temporary Pod in the same namespace, the short name web resolves to the Service. Then list the endpoints behind it. Use EndpointSlices: the older kubectl get endpoints reads the v1 Endpoints API, which is deprecated since v1.33 and prints a warning. Keep the JP variable for step 6.

Terminal
kubectl run probe --rm -i --restart=Never --image=busybox:1.37 -- \
  wget -qO- http://web/
JP='{range .items[*].endpoints[*]}{.targetRef.name}{" ready="}'
JP+='{.conditions.ready}{"\n"}{end}'
kubectl get endpointslices -l kubernetes.io/service-name=web -o jsonpath="$JP"
Illustrative output
hello from web-7d4b9c6f8d-8xq4n (v1)
pod "probe" deleted from default namespace
web-7d4b9c6f8d-2fj9q ready=true
web-7d4b9c6f8d-8xq4n ready=true
web-7d4b9c6f8d-tz6lw ready=true

06. Step 5: Expose it with a Gateway API HTTPRoute

A ClusterIP Service is reachable only inside the cluster. To route HTTP from outside, Kubernetes offers two APIs. Ingress (networking.k8s.io/v1) is older and still supported, but its features vary by controller, and the popular ingress-nginx controller was retired in March 2026. The Gateway API (gateway.networking.k8s.io/v1) splits the job into roles: a GatewayClass names the controller, a Gateway is a listener owned by the platform team, and an HTTPRoute owned by the app team attaches to it and sends matching requests to a Service.

Both APIs are only specifications. Nothing happens until a controller that implements them runs in the cluster, so first install Envoy Gateway, which also installs the Gateway API CRDs.

Terminal
kubectl apply --server-side \
  -f https://github.com/envoyproxy/gateway/releases/download/v1.9.4/install.yaml
kubectl wait --timeout=5m -n envoy-gateway-system \
  deployment/envoy-gateway --for=condition=Available

Save route.yaml. The route accepts requests for the host web.example.test on the Gateway web-gw and forwards them to port 80 of the Service web, which the Service sends on to port 8080 of a ready Pod. kind has no cloud load balancer, so the Gateway may never get an external address; forward a local port to the Envoy Service instead. The second curl uses a host that no route matches.

YAML · route.yaml
apiVersion: gateway.networking.k8s.io/v1
kind: GatewayClass
metadata:
  name: eg
spec:
  controllerName: gateway.envoyproxy.io/gatewayclass-controller
---
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
  name: web-gw
spec:
  gatewayClassName: eg
  listeners:
    - name: http
      protocol: HTTP
      port: 80
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: web
spec:
  parentRefs:
    - name: web-gw
  hostnames: ["web.example.test"]
  rules:
    - matches:
        - path: {type: PathPrefix, value: /}
      backendRefs:
        - name: web
          port: 80
Terminal
kubectl apply -f route.yaml
kubectl get httproute web \
  -o jsonpath='{.status.parents[0].conditions[?(@.type=="Accepted")].status}{"\n"}'
ENVOY_SVC=$(kubectl get svc -n envoy-gateway-system \
  -l gateway.envoyproxy.io/owning-gateway-name=web-gw \
  -o jsonpath='{.items[0].metadata.name}')
kubectl -n envoy-gateway-system port-forward "svc/$ENVOY_SVC" 8888:80 &
sleep 3
curl -s -H 'Host: web.example.test' localhost:8888/
curl -s -o /dev/null -w '%{http_code}\n' -H 'Host: other.test' localhost:8888/
Illustrative output
True
Forwarding from 127.0.0.1:8888 -> 10080
hello from web-7d4b9c6f8d-tz6lw (v1)
404

07. Step 6: Break readiness, then liveness

Make one replica unready. With periodSeconds: 5 and failureThreshold: 3, the kubelet marks it not ready 10 to 15 seconds after the switch, then the EndpointSlice controller updates the slice and kube-proxy stops sending it new connections. Requests that reach it before that can still fail, so pick probe timings that fit your error budget.

Terminal · readiness
POD=$(kubectl get pods -l app=web -o jsonpath='{.items[0].metadata.name}')
kubectl exec "$POD" -- touch /tmp/drain
sleep 20
kubectl get pods -l app=web
kubectl get endpointslices -l kubernetes.io/service-name=web -o jsonpath="$JP"
kubectl exec "$POD" -- rm /tmp/drain
Illustrative output
NAME                   READY   STATUS    RESTARTS   AGE
web-7d4b9c6f8d-2fj9q   0/1     Running   0          6m2s
web-7d4b9c6f8d-8xq4n   1/1     Running   0          6m2s
web-7d4b9c6f8d-tz6lw   1/1     Running   0          6m2s
web-7d4b9c6f8d-2fj9q ready=false
web-7d4b9c6f8d-8xq4n ready=true
web-7d4b9c6f8d-tz6lw ready=true

The Pod stayed Running with RESTARTS 0: readiness only moves traffic. Now wedge the same Pod. After three liveness failures 10 seconds apart, the kubelet restarts the container. The new container starts with a fresh filesystem, so /tmp/wedged is gone and it recovers.

Terminal · liveness
kubectl exec "$POD" -- touch /tmp/wedged
sleep 45
kubectl get pod "$POD"
kubectl get events --field-selector involvedObject.name="$POD" \
  --sort-by=.lastTimestamp -o custom-columns=REASON:.reason,MESSAGE:.message \
  | grep -E 'Liveness|Killing'
Illustrative output
NAME                   READY   STATUS    RESTARTS      AGE
web-7d4b9c6f8d-2fj9q   1/1     Running   1 (12s ago)   7m10s
Unhealthy   Liveness probe failed: HTTP probe failed with statuscode: 500
Killing     Container app failed liveness probe, will be restarted

Two design rules follow. Liveness should detect only states that a restart fixes, such as a deadlock; never point it at a database or another service, or one outage restarts every replica at once. Readiness should say whether this instance can serve now: warm-up done, not overloaded. Be careful with shared dependencies there too: if every replica checks the same database, a short database blip makes them all unready together, and the Service has no endpoints at all.

Keep the cluster: lesson 4 builds on it. To remove everything later, run kind delete cluster --name k8s-lab.

08. Check your understanding

Practice check · 3 questions

Probes and routing in this lab

Three questions about what you saw in steps 4 to 6.

Q1. One replica of `web` fails its readiness probe for two minutes while its liveness probe keeps passing. Which state matches?
Q2. Every replica reports not ready whenever the shared database is unreachable. The database is down for 30 seconds. What do clients of the Service see?
Q3. On a fresh cluster you apply a Gateway and an HTTPRoute, and both are stored without errors, but no traffic reaches the app. What is the most likely cause?
Practice only: not graded, not saved, not evidence.

09. Apply it

Move toward the skill project, which runs your own containerised service:

  • Replace the image and command with the service you containerised in the containers skill, keeping a separate liveness and readiness endpoint.
  • Measure its memory with kubectl top pod (lesson 4 installs metrics-server) and set requests from what you observe, not from a template.
  • Add a second HTTPRoute rule that sends /api to a different Service, and check both paths through the Gateway.

10. Review prompt

Without looking back, explain: what the scheduler uses to place a Pod; what happens when a container exceeds its memory limit and when it exceeds a CPU limit; what makes a Pod Guaranteed; what each of the three probes decides and roughly how long your settings took to react; why a database check belongs in neither liveness nor, without care, readiness; and which objects you need, besides a Service, to route outside traffic with the Gateway API.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check