TExcelTAD
Home › Kubernetes › Mini Project: A 3-Tier App

Mini Project: A 3-Tier App

In this project you'll deploy a classic three-tier web shop to Kubernetes, and build a Python validator that catches the mistakes that most often break such deployments before they reach a cluster.

text
            Internet
               │  https://shop.example.com
         ┌─────▼─────┐
         │  Ingress  │  /api -> api:80     / -> frontend:80
         └──┬─────┬──┘
   ┌────────▼┐   ┌▼────────┐
   │frontend │   │   api   │  Deployment (2-10 replicas, HPA)
   │ nginx x2│   │ x3      │──── ConfigMap api-config, Secret db-credentials
   └─────────┘   └────┬────┘
                      │ postgres://db:5432   (NetworkPolicy: only api may connect)
                 ┌────▼────┐
                 │   db    │  StatefulSet + headless Service + PVC per Pod
                 └─────────┘

Step 1: The manifests

All objects live in the shop namespace. Save this as shop.yaml (one file, several documents) and apply it to a test cluster with kubectl apply -f shop.yaml once an ingress controller is installed (here Traefik, which k3d clusters include by default; ingress-nginx is retired, so don't install it).

yaml
apiVersion: v1
kind: Namespace
metadata:
  name: shop
  labels:
    pod-security.kubernetes.io/enforce: baseline
---
apiVersion: v1
kind: ConfigMap
metadata: {name: api-config, namespace: shop}
data:
  DATABASE_HOST: db
  DATABASE_NAME: shop
  LOG_LEVEL: info
---
apiVersion: v1
kind: Secret
metadata: {name: db-credentials, namespace: shop}
type: Opaque
stringData:
  username: shop
  password: change-me          # use Sealed Secrets / External Secrets in real life
---
apiVersion: v1
kind: Service
metadata: {name: db, namespace: shop}
spec:
  clusterIP: None
  selector: {app: db}
  ports: [{name: postgres, port: 5432, targetPort: 5432}]
---
apiVersion: apps/v1
kind: StatefulSet
metadata: {name: db, namespace: shop}
spec:
  serviceName: db
  replicas: 1
  selector: {matchLabels: {app: db}}
  template:
    metadata: {labels: {app: db, tier: data}}
    spec:
      containers:
        - name: postgres
          image: postgres:17.6
          ports: [{containerPort: 5432}]
          env:
            - name: POSTGRES_USER
              valueFrom: {secretKeyRef: {name: db-credentials, key: username}}
            - name: POSTGRES_PASSWORD
              valueFrom: {secretKeyRef: {name: db-credentials, key: password}}
            - {name: PGDATA, value: /var/lib/postgresql/data/pgdata}
          readinessProbe:
            exec: {command: [pg_isready, -U, shop]}
          resources:
            requests: {cpu: 250m, memory: 512Mi}
            limits: {memory: 1Gi}
          volumeMounts: [{name: data, mountPath: /var/lib/postgresql/data}]
  volumeClaimTemplates:
    - metadata: {name: data}
      spec:
        accessModes: [ReadWriteOnce]
        resources: {requests: {storage: 10Gi}}
---
apiVersion: apps/v1
kind: Deployment
metadata: {name: api, namespace: shop}
spec:
  replicas: 3
  selector: {matchLabels: {app: api}}
  template:
    metadata: {labels: {app: api, tier: backend}}
    spec:
      containers:
        - name: api
          image: ghcr.io/acme/shop-api:2.4.0
          ports: [{name: http, containerPort: 8000}]
          envFrom: [{configMapRef: {name: api-config}}]
          env:
            - name: DATABASE_PASSWORD
              valueFrom: {secretKeyRef: {name: db-credentials, key: password}}
          readinessProbe: {httpGet: {path: /ready, port: http}}
          livenessProbe: {httpGet: {path: /healthz, port: http}}
          resources:
            requests: {cpu: 200m, memory: 256Mi}
            limits: {memory: 512Mi}
---
apiVersion: v1
kind: Service
metadata: {name: api, namespace: shop}
spec:
  selector: {app: api}
  ports: [{port: 80, targetPort: http}]
---
apiVersion: apps/v1
kind: Deployment
metadata: {name: frontend, namespace: shop}
spec:
  replicas: 2
  selector: {matchLabels: {app: frontend}}
  template:
    metadata: {labels: {app: frontend, tier: web}}
    spec:
      containers:
        - name: nginx
          image: ghcr.io/acme/shop-frontend:1.8.3
          ports: [{containerPort: 8080}]
          readinessProbe: {httpGet: {path: /, port: 8080}}
          resources:
            requests: {cpu: 50m, memory: 64Mi}
            limits: {memory: 128Mi}
---
apiVersion: v1
kind: Service
metadata: {name: frontend, namespace: shop}
spec:
  selector: {app: frontend}
  ports: [{port: 80, targetPort: 8080}]
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata: {name: shop, namespace: shop}
spec:
  ingressClassName: traefik
  rules:
    - host: shop.example.com
      http:
        paths:
          - {path: /api, pathType: Prefix, backend: {service: {name: api, port: {number: 80}}}}
          - {path: /, pathType: Prefix, backend: {service: {name: frontend, port: {number: 80}}}}
---
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata: {name: api, namespace: shop}
spec:
  scaleTargetRef: {apiVersion: apps/v1, kind: Deployment, name: api}
  minReplicas: 2
  maxReplicas: 10
  metrics:
    - type: Resource
      resource: {name: cpu, target: {type: Utilization, averageUtilization: 70}}
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: {name: db-only-from-api, namespace: shop}
spec:
  podSelector: {matchLabels: {app: db}}
  policyTypes: [Ingress]
  ingress:
    - from: [{podSelector: {matchLabels: {app: api}}}]
      ports: [{protocol: TCP, port: 5432}]
bash
kubectl apply -f shop.yaml
kubectl get all -n shop
kubectl rollout status deploy/api -n shop
curl -H 'Host: shop.example.com' http://<ingress-ip>/api/health

Sample output:

text
namespace/shop created
configmap/api-config created
secret/db-credentials created
service/db created
statefulset.apps/db created
deployment.apps/api created
service/api created
deployment.apps/frontend created
service/frontend created
ingress.networking.k8s.io/shop created
horizontalpodautoscaler.autoscaling/api created
networkpolicy.networking.k8s.io/db-only-from-api created

Step 2: Load and index the bundle

The validator starts by parsing every document and indexing objects by (kind, name). We use a shortened copy of the bundle here so each step stays readable; the final step checks the whole application.

python · try it yourself
import yaml

BUNDLE = """
kind: ConfigMap
metadata: {name: api-config, namespace: shop}
data: {DATABASE_HOST: db, LOG_LEVEL: info}
---
kind: Secret
metadata: {name: db-credentials, namespace: shop}
stringData: {username: shop, password: change-me}
---
kind: Deployment
metadata: {name: api, namespace: shop}
spec:
  replicas: 3
  selector: {matchLabels: {app: api}}
  template:
    metadata: {labels: {app: api, tier: backend}}
    spec:
      containers: [{name: api, image: "ghcr.io/acme/shop-api:2.4.0"}]
---
kind: Service
metadata: {name: api, namespace: shop}
spec: {selector: {app: api}, ports: [{port: 80, targetPort: http}]}
"""

docs = [d for d in yaml.safe_load_all(BUNDLE) if d]
index = {(d["kind"], d["metadata"]["name"]): d for d in docs}

print(f"{len(docs)} objects")
for kind, name in index:
    ns = index[(kind, name)]["metadata"].get("namespace", "-")
    print(f"  {kind:11} {name:15} ns={ns}")
4 objects
  ConfigMap   api-config      ns=shop
  Secret      db-credentials  ns=shop
  Deployment  api             ns=shop
  Service     api             ns=shop

Step 3: Selectors must match their templates

A Deployment or StatefulSet whose selector doesn't match its own Pod template labels is rejected by the API server. A Service whose selector matches no workload is accepted but silently has no endpoints, which is much worse. Let's check both:

python · try it yourself
import yaml

docs = list(yaml.safe_load_all("""
kind: Deployment
metadata: {name: api}
spec:
  selector: {matchLabels: {app: api}}
  template: {metadata: {labels: {app: api, tier: backend}}}
---
kind: Deployment
metadata: {name: frontend}
spec:
  selector: {matchLabels: {app: frontend}}
  template: {metadata: {labels: {app: front-end}}}
---
kind: Service
metadata: {name: api}
spec: {selector: {app: api}}
---
kind: Service
metadata: {name: cache}
spec: {selector: {app: redis}}
"""))

WORKLOADS = ("Deployment", "StatefulSet", "DaemonSet")

def selected(selector, labels):
    return all(labels.get(k) == v for k, v in selector.items())

def check_selectors(docs):
    problems = []
    for d in docs:
        if d["kind"] in WORKLOADS:
            sel = d["spec"]["selector"]["matchLabels"]
            labels = d["spec"]["template"]["metadata"]["labels"]
            if not selected(sel, labels):
                problems.append(f"{d['kind']}/{d['metadata']['name']}: selector {sel} does not match template labels {labels}")
    for svc in (d for d in docs if d["kind"] == "Service"):
        targets = [w["metadata"]["name"] for w in docs if w["kind"] in WORKLOADS
                   and selected(svc["spec"]["selector"], w["spec"]["template"]["metadata"]["labels"])]
        if not targets:
            problems.append(f"Service/{svc['metadata']['name']}: selector {svc['spec']['selector']} matches no workload")
    return problems

for p in check_selectors(docs) or ["selectors ok"]:
    print(p)
Deployment/frontend: selector {'app': 'frontend'} does not match template labels {'app': 'front-end'}
Service/cache: selector {'app': 'redis'} matches no workload

Step 4: Ports and references

Two more silent killers: a Service targetPort that the container doesn't expose (by number or by name), and an envFrom/secretKeyRef pointing at a ConfigMap or Secret (or key) that doesn't exist, which leaves the Pod in CreateContainerConfigError.

python · try it yourself
import yaml

docs = list(yaml.safe_load_all("""
kind: ConfigMap
metadata: {name: api-config}
data: {DATABASE_HOST: db}
---
kind: Secret
metadata: {name: db-credentials}
stringData: {username: shop, password: change-me}
---
kind: Deployment
metadata: {name: api}
spec:
  template:
    metadata: {labels: {app: api}}
    spec:
      containers:
        - name: api
          ports: [{name: http, containerPort: 8000}]
          envFrom: [{configMapRef: {name: api-config}}]
          env:
            - {name: DATABASE_PASSWORD, valueFrom: {secretKeyRef: {name: db-credentials, key: password}}}
            - {name: DATABASE_USER, valueFrom: {secretKeyRef: {name: db-credentials, key: user}}}
---
kind: Deployment
metadata: {name: frontend}
spec:
  template:
    metadata: {labels: {app: frontend}}
    spec:
      containers:
        - name: nginx
          ports: [{containerPort: 8080}]
          envFrom: [{configMapRef: {name: frontend-config}}]
---
kind: Service
metadata: {name: api}
spec: {selector: {app: api}, ports: [{port: 80, targetPort: http}]}
---
kind: Service
metadata: {name: frontend}
spec: {selector: {app: frontend}, ports: [{port: 80, targetPort: 80}]}
"""))

by_kind = lambda kind: {d["metadata"]["name"]: d for d in docs if d["kind"] == kind}
configmaps, secrets, deployments = by_kind("ConfigMap"), by_kind("Secret"), by_kind("Deployment")

def check_ports():
    out = []
    for svc in by_kind("Service").values():
        for dep in deployments.values():
            if not all(dep["spec"]["template"]["metadata"]["labels"].get(k) == v for k, v in svc["spec"]["selector"].items()):
                continue
            exposed = set()
            for c in dep["spec"]["template"]["spec"]["containers"]:
                for p in c.get("ports", []):
                    exposed.add(p["containerPort"])
                    if "name" in p:
                        exposed.add(p["name"])
            for port in svc["spec"]["ports"]:
                if port["targetPort"] not in exposed:
                    out.append(f"Service/{svc['metadata']['name']}: targetPort {port['targetPort']!r} not exposed by "
                               f"Deployment/{dep['metadata']['name']} (has {sorted(map(str, exposed))})")
    return out

def check_refs():
    out = []
    for dep in deployments.values():
        for c in dep["spec"]["template"]["spec"]["containers"]:
            for ef in c.get("envFrom", []):
                name = ef["configMapRef"]["name"]
                if name not in configmaps:
                    out.append(f"Deployment/{dep['metadata']['name']}: ConfigMap {name!r} not found")
            for e in c.get("env", []):
                ref = e.get("valueFrom", {}).get("secretKeyRef")
                if ref:
                    secret = secrets.get(ref["name"])
                    if secret is None:
                        out.append(f"Deployment/{dep['metadata']['name']}: Secret {ref['name']!r} not found")
                    elif ref["key"] not in secret.get("stringData", {}) | secret.get("data", {}):
                        out.append(f"Deployment/{dep['metadata']['name']}: key {ref['key']!r} not in Secret {ref['name']!r}")
    return out

for p in check_ports() + check_refs() or ["ports and references ok"]:
    print(p)
Service/frontend: targetPort 80 not exposed by Deployment/frontend (has ['8080'])
Deployment/api: key 'user' not in Secret 'db-credentials'
Deployment/frontend: ConfigMap 'frontend-config' not found

Step 5: Production readiness rules

Finally some policy checks that aren't errors for Kubernetes but are for us: pinned image tags, CPU/memory requests, a memory limit, and a readiness probe on every container that serves traffic.

python · try it yourself
import yaml

containers = yaml.safe_load("""
- workload: Deployment/api
  name: api
  image: ghcr.io/acme/shop-api:2.4.0
  readinessProbe: {httpGet: {path: /ready, port: http}}
  resources: {requests: {cpu: 200m, memory: 256Mi}, limits: {memory: 512Mi}}
- workload: Deployment/frontend
  name: nginx
  image: ghcr.io/acme/shop-frontend:latest
  resources: {requests: {cpu: 50m}}
- workload: StatefulSet/db
  name: postgres
  image: postgres:17.6
  readinessProbe: {exec: {command: [pg_isready]}}
  resources: {requests: {cpu: 250m, memory: 512Mi}}
""")

RULES = [
    ("pinned tag", lambda c: ":" in c["image"].rsplit("/", 1)[-1] and not c["image"].endswith(":latest")),
    ("cpu request", lambda c: "cpu" in c.get("resources", {}).get("requests", {})),
    ("memory request", lambda c: "memory" in c.get("resources", {}).get("requests", {})),
    ("memory limit", lambda c: "memory" in c.get("resources", {}).get("limits", {})),
    ("readiness probe", lambda c: "readinessProbe" in c),
]

print(f"{'container':29}" + "".join(f"{name:>16}" for name, _ in RULES))
failures = 0
for c in containers:
    marks = []
    for name, rule in RULES:
        ok = rule(c)
        failures += not ok
        marks.append("ok" if ok else "MISSING")
    print(f"{c['workload'] + '/' + c['name']:29}" + "".join(f"{m:>16}" for m in marks))
print(f"{failures} problem(s)")
container                          pinned tag     cpu request  memory request    memory limit readiness probe
Deployment/api/api                         ok              ok              ok              ok              ok
Deployment/frontend/nginx             MISSING              ok         MISSING         MISSING         MISSING
StatefulSet/db/postgres                    ok              ok              ok         MISSING              ok
5 problem(s)

Step 6: Will it fit? A scheduling dry run

Before deploying, check that the cluster has room for every replica at its requested size, including the HPA's maximum for the api. This model places Pods on three worker nodes with a "least allocated" strategy and reports headroom:

python · try it yourself
nodes = {name: {"cpu": 900, "mem": 4000} for name in ["worker-1", "worker-2", "worker-3"]}   # allocatable
used = {name: {"cpu": 0, "mem": 0} for name in nodes}
placement = {}

def place(pod, cpu, mem):
    fits = [n for n in nodes if used[n]["cpu"] + cpu <= nodes[n]["cpu"] and used[n]["mem"] + mem <= nodes[n]["mem"]]
    if not fits:
        return None
    best = min(fits, key=lambda n: (used[n]["cpu"] / nodes[n]["cpu"], n))      # least allocated first
    used[best]["cpu"] += cpu
    used[best]["mem"] += mem
    placement[pod] = best
    return best

def plan(api_replicas):
    for n in used:
        used[n] = {"cpu": 0, "mem": 0}
    placement.clear()
    workloads = [("db", 1, 250, 512), ("api", api_replicas, 200, 256), ("frontend", 2, 50, 64)]
    pending = []
    for name, replicas, cpu, mem in workloads:
        for i in range(replicas):
            if place(f"{name}-{i}", cpu, mem) is None:
                pending.append(f"{name}-{i}")
    return pending

for replicas in [3, 10]:
    pending = plan(replicas)
    print(f"api replicas = {replicas}:")
    for n in nodes:
        pods = [p for p, node in placement.items() if node == n]
        print(f"  {n}: cpu {used[n]['cpu']:4}/{nodes[n]['cpu']}m  pods {pods}")
    print("  pending:", pending or "none")
api replicas = 3:
  worker-1: cpu  300/900m  pods ['db-0', 'frontend-1']
  worker-2: cpu  400/900m  pods ['api-0', 'api-2']
  worker-3: cpu  250/900m  pods ['api-1', 'frontend-0']
  pending: none
api replicas = 10:
  worker-1: cpu  750/900m  pods ['db-0', 'api-4', 'api-7', 'frontend-0', 'frontend-1']
  worker-2: cpu  800/900m  pods ['api-0', 'api-2', 'api-5', 'api-8']
  worker-3: cpu  800/900m  pods ['api-1', 'api-3', 'api-6', 'api-9']
  pending: none

At the HPA's maximum of 10 api replicas, the requests still fit, but only just: you'd want a cluster autoscaler or one more node before a traffic spike.

Step 7: The complete validator

Now combine the checks and run them on the whole application from Step 1 (written in compact flow style, leaving out the fields the validator doesn't inspect, such as the volume claim and the NetworkPolicy). A clean result means every selector, port and reference lines up and every container meets the production rules:

python · try it yourself
import yaml

SHOP_YAML = """
apiVersion: v1
kind: Namespace
metadata: {name: shop}
---
apiVersion: v1
kind: ConfigMap
metadata: {name: api-config, namespace: shop}
data: {DATABASE_HOST: db, DATABASE_NAME: shop, LOG_LEVEL: info}
---
apiVersion: v1
kind: Secret
metadata: {name: db-credentials, namespace: shop}
stringData: {username: shop, password: change-me}
---
apiVersion: v1
kind: Service
metadata: {name: db, namespace: shop}
spec: {clusterIP: None, selector: {app: db}, ports: [{name: postgres, port: 5432, targetPort: 5432}]}
---
apiVersion: apps/v1
kind: StatefulSet
metadata: {name: db, namespace: shop}
spec:
  serviceName: db
  replicas: 1
  selector: {matchLabels: {app: db}}
  template:
    metadata: {labels: {app: db, tier: data}}
    spec:
      containers:
        - name: postgres
          image: postgres:17.6
          ports: [{containerPort: 5432}]
          env:
            - {name: POSTGRES_USER, valueFrom: {secretKeyRef: {name: db-credentials, key: username}}}
            - {name: POSTGRES_PASSWORD, valueFrom: {secretKeyRef: {name: db-credentials, key: password}}}
          readinessProbe: {exec: {command: [pg_isready, -U, shop]}}
          resources: {requests: {cpu: 250m, memory: 512Mi}, limits: {memory: 1Gi}}
---
apiVersion: apps/v1
kind: Deployment
metadata: {name: api, namespace: shop}
spec:
  replicas: 3
  selector: {matchLabels: {app: api}}
  template:
    metadata: {labels: {app: api, tier: backend}}
    spec:
      containers:
        - name: api
          image: ghcr.io/acme/shop-api:2.4.0
          ports: [{name: http, containerPort: 8000}]
          envFrom: [{configMapRef: {name: api-config}}]
          env:
            - {name: DATABASE_PASSWORD, valueFrom: {secretKeyRef: {name: db-credentials, key: password}}}
          readinessProbe: {httpGet: {path: /ready, port: http}}
          resources: {requests: {cpu: 200m, memory: 256Mi}, limits: {memory: 512Mi}}
---
apiVersion: v1
kind: Service
metadata: {name: api, namespace: shop}
spec: {selector: {app: api}, ports: [{port: 80, targetPort: http}]}
---
apiVersion: apps/v1
kind: Deployment
metadata: {name: frontend, namespace: shop}
spec:
  replicas: 2
  selector: {matchLabels: {app: frontend}}
  template:
    metadata: {labels: {app: frontend, tier: web}}
    spec:
      containers:
        - name: nginx
          image: ghcr.io/acme/shop-frontend:1.8.3
          ports: [{containerPort: 8080}]
          readinessProbe: {httpGet: {path: /, port: 8080}}
          resources: {requests: {cpu: 50m, memory: 64Mi}, limits: {memory: 128Mi}}
---
apiVersion: v1
kind: Service
metadata: {name: frontend, namespace: shop}
spec: {selector: {app: frontend}, ports: [{port: 80, targetPort: 8080}]}
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata: {name: shop, namespace: shop}
spec:
  rules:
    - host: shop.example.com
      http:
        paths:
          - {path: /api, pathType: Prefix, backend: {service: {name: api, port: {number: 80}}}}
          - {path: /, pathType: Prefix, backend: {service: {name: frontend, port: {number: 80}}}}
---
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata: {name: api, namespace: shop}
spec:
  scaleTargetRef: {apiVersion: apps/v1, kind: Deployment, name: api}
  minReplicas: 2
  maxReplicas: 10
"""

WORKLOADS = ("Deployment", "StatefulSet")

def validate(text):
    docs = [d for d in yaml.safe_load_all(text) if d]
    objs = {}
    for d in docs:
        objs.setdefault(d["kind"], {})[d["metadata"]["name"]] = d
    get = lambda kind: objs.get(kind, {})
    problems, checks = [], 0

    def check(ok, message):
        nonlocal checks
        checks += 1
        if not ok:
            problems.append(message)

    def matches(sel, labels):
        return all(labels.get(k) == v for k, v in sel.items())

    workloads = [w for kind in WORKLOADS for w in get(kind).values()]
    for w in workloads:
        wid = f"{w['kind']}/{w['metadata']['name']}"
        labels = w["spec"]["template"]["metadata"]["labels"]
        check(matches(w["spec"]["selector"]["matchLabels"], labels), f"{wid}: selector/template mismatch")
        for c in w["spec"]["template"]["spec"]["containers"]:
            res = c.get("resources", {})
            check(not c["image"].endswith(":latest") and ":" in c["image"].rsplit("/", 1)[-1], f"{wid}: unpinned image")
            check({"cpu", "memory"} <= set(res.get("requests", {})), f"{wid}: missing requests")
            check("memory" in res.get("limits", {}), f"{wid}: missing memory limit")
            check("readinessProbe" in c, f"{wid}: missing readiness probe")
            for ef in c.get("envFrom", []):
                check(ef["configMapRef"]["name"] in get("ConfigMap"), f"{wid}: missing ConfigMap {ef['configMapRef']['name']}")
            for e in c.get("env", []):
                ref = e.get("valueFrom", {}).get("secretKeyRef")
                if ref:
                    secret = get("Secret").get(ref["name"], {})
                    check(ref["key"] in secret.get("stringData", {}), f"{wid}: missing Secret key {ref['name']}/{ref['key']}")
    for svc in get("Service").values():
        sid = f"Service/{svc['metadata']['name']}"
        targets = [w for w in workloads if matches(svc["spec"]["selector"], w["spec"]["template"]["metadata"]["labels"])]
        check(bool(targets), f"{sid}: selects no workload")
        for w in targets:
            exposed = {v for c in w["spec"]["template"]["spec"]["containers"] for p in c.get("ports", [])
                       for v in (p["containerPort"], p.get("name"))}
            for port in svc["spec"]["ports"]:
                check(port["targetPort"] in exposed, f"{sid}: targetPort {port['targetPort']} not exposed")
    for ing in get("Ingress").values():
        for rule in ing["spec"]["rules"]:
            for p in rule["http"]["paths"]:
                backend = p["backend"]["service"]
                svc = get("Service").get(backend["name"])
                check(svc is not None and any(sp["port"] == backend["port"]["number"] for sp in svc["spec"]["ports"]),
                      f"Ingress/{ing['metadata']['name']}: {p['path']} -> unknown service port {backend['name']}:{backend['port']['number']}")
    for hpa in get("HorizontalPodAutoscaler").values():
        ref = hpa["spec"]["scaleTargetRef"]
        check(ref["name"] in get(ref["kind"]), f"HPA/{hpa['metadata']['name']}: target {ref['kind']}/{ref['name']} not found")
    return docs, checks, problems

docs, checks, problems = validate(SHOP_YAML)
print(f"{len(docs)} objects, {checks} checks, {len(problems)} problem(s)")
for p in problems:
    print("  -", p)

# Now simulate a careless edit: a renamed Service and a typo in the image tag
broken = SHOP_YAML.replace("metadata: {name: frontend, namespace: shop}\nspec: {selector", "metadata: {name: web, namespace: shop}\nspec: {selector")
broken = broken.replace("shop-api:2.4.0", "shop-api:latest")
docs, checks, problems = validate(broken)
print(f"after edit: {checks} checks, {len(problems)} problem(s)")
for p in problems:
    print("  -", p)
11 objects, 28 checks, 0 problem(s)
after edit: 28 checks, 2 problem(s)
  - Deployment/api: unpinned image
  - Ingress/shop: / -> unknown service port frontend:80

The validator caught both mistakes: the unpinned image, and the Ingress route pointing at a Service that no longer exists (which would return 503 errors in production).

Ideas to extend the project

  • Add a check that every Deployment in the bundle with an HPA has minReplicas <= replicas <= maxReplicas.
  • Check NetworkPolicies: does every Pod that must reach the database (app: api) have an allowing rule, and no one else?
  • Read the bundle from a real file with open("shop.yaml") in a local Python, and run the validator in your CI pipeline before kubectl apply or before Argo CD syncs.
  • Compare with real tools that do this professionally: kubeconform (schema validation), kube-linter and polaris (best practices), conftest (policies in Rego).

Test yourself

Why is a Service whose selector matches no Pods dangerous?

  1. The API server rejects it
  2. It is accepted but has no endpoints, so traffic silently fails
  3. It deletes Pods
  4. It creates extra Pods

In this project, which object stops the frontend Pods from connecting to the database?

  1. The Ingress
  2. The HPA
  3. The NetworkPolicy db-only-from-api
  4. The headless Service

The api Service uses targetPort: http. What must be true for it to work?

  1. The Service must be named http
  2. A container port in the api Pods must be named http
  3. The Ingress must use port http
  4. Nothing, names are ignored