Kubernetes Labs · Lab 9 of 9
A Production-Grade Cluster: Guardrails, Least Privilege, Network Policy and GitOps
Turn a namespace into a production namespace with Pod Security admission, quotas, default limits, least-privilege RBAC and default-deny networking, then hand deployments to Argo CD so Git becomes the only way to change the cluster, and watch it undo a manual change.
- Environment
- Production
- Level
- Advanced
- Time
- About 75 min
- Cost
- Free
You will build
A shop-prod namespace that rejects unsafe pods, caps resources, limits what CI can do and who can connect, and an
Argo CD installation that keeps an app in sync with Git and reverts drift.
Before you start
- Lab: Environments with Kustomize: One Base, a Dev and a Prod Overlay
About 3 GB of free memory for Argo CD on your kind cluster
The earlier labs made workloads reliable. Production also needs the cluster to be safe by default: a mistake or a compromised pod should be stopped by policy, not by luck. This lab builds the guardrails most platform teams put on every production namespace, all with built-in Kubernetes features:
- Pod Security admission rejects pods that run as root, are privileged or keep Linux capabilities.
- ResourceQuota caps what a namespace may consume; LimitRange fills in defaults for containers that forget.
- RBAC gives each identity only the verbs it needs; CI can deploy but can't read Secrets.
- NetworkPolicy denies all incoming traffic, then allows exactly what is needed.
Then the deployment model changes. With GitOps, nobody runs kubectl apply against production. A controller
inside the cluster, Argo CD, continuously compares the cluster with a Git repository and applies the
difference. Changes happen by pull request; rollbacks are Git reverts; manual edits are detected and undone.
Every output below was captured from a real run on kind 0.33 with Kubernetes 1.37. Pod names, IP addresses, ages and cluster ports are generated, so yours will differ; everything else should match.
Project structure
platform/
├── namespace.yaml # shop-prod with Pod Security "restricted"
├── guardrails.yaml # ResourceQuota + LimitRange
├── rbac.yaml # ServiceAccount, Role and RoleBinding for the CI deployer
├── app.yaml # a Deployment that passes "restricted", and its Service
├── bad-pod.yaml # a pod that breaks the policy on purpose
├── networkpolicies.yaml # default deny + allow from namespace edge
└── argocd/
├── guestbook-app.yaml # an Application from a public example repository
└── shop-prod-app.yaml # the same for your own repository (lab 5 layout)
Steps
-
1A namespace with Pod Security admission
Pod Security admission is built into the API server; a namespace label turns it on.
enforce: restrictedrejects non-compliant pods;warnalso prints warnings when you apply.namespace.yaml # Pod Security admission: "restricted" rejects pods that run as root, keep capabilities or escalate privileges. apiVersion: v1 kind: Namespace metadata: name: shop-prod labels: pod-security.kubernetes.io/enforce: restricted pod-security.kubernetes.io/enforce-version: latest pod-security.kubernetes.io/warn: restricted -
2Quotas and default limits
The ResourceQuota stops one namespace from taking the whole cluster (and here forbids LoadBalancer Services, which would create cloud load balancers outside your Gateway). The LimitRange gives containers that don't set requests or limits sensible defaults, and caps memory per container.
guardrails.yaml # Caps for the whole namespace, and defaults for containers that don't set their own. apiVersion: v1 kind: ResourceQuota metadata: name: shop-prod namespace: shop-prod spec: hard: requests.cpu: "2" requests.memory: 2Gi limits.memory: 4Gi pods: "20" services.loadbalancers: "0" --- apiVersion: v1 kind: LimitRange metadata: name: defaults namespace: shop-prod spec: limits: - type: Container defaultRequest: cpu: 50m memory: 64Mi default: memory: 128Mi max: memory: 1Gi -
3Least-privilege RBAC for the deployer
A Role lists allowed verbs on resources in one namespace; a RoleBinding gives it to an identity. The CI deployer may manage Deployments, Services and ConfigMaps and read pods and logs. It can't read Secrets, touch other namespaces or change RBAC.
rbac.yaml # The CI deployer may manage workloads in shop-prod only, and can't read Secrets. apiVersion: v1 kind: ServiceAccount metadata: name: deployer namespace: shop-prod --- apiVersion: rbac.authorization.k8s.io/v1 kind: Role metadata: name: deployer namespace: shop-prod rules: - apiGroups: ["apps"] resources: ["deployments"] verbs: ["get", "list", "watch", "create", "update", "patch"] - apiGroups: [""] resources: ["services", "configmaps"] verbs: ["get", "list", "watch", "create", "update", "patch"] - apiGroups: [""] resources: ["pods", "pods/log"] verbs: ["get", "list", "watch"] --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding metadata: name: deployer namespace: shop-prod subjects: - kind: ServiceAccount name: deployer namespace: shop-prod roleRef: apiGroup: rbac.authorization.k8s.io kind: Role name: deployer -
4Apply the guardrails and try a privileged pod
The pod in
bad-pod.yamlasks forprivileged: trueand sets nothing else. Admission rejects it before it is stored, and the error lists every rule it breaks: a ready-made checklist for fixing manifests.Run kubectl apply -f namespace.yaml -f guardrails.yaml -f rbac.yaml kubectl apply -f bad-pod.yamlExpected output
namespace/shop-prod created resourcequota/shop-prod created limitrange/defaults created serviceaccount/deployer created role.rbac.authorization.k8s.io/deployer created rolebinding.rbac.authorization.k8s.io/deployer created Error from server (Forbidden): error when creating "bad-pod.yaml": pods "root-shell" is forbidden: violates PodSecurity "restricted:latest": privileged (container "shell" must not set securityContext.privileged=true), allowPrivilegeEscalation != false (container "shell" must set securityContext.allowPrivilegeEscalation=false), unrestricted capabilities (container "shell" must set securityContext.capabilities.drop=["ALL"]), runAsNonRoot != true (pod or container "shell" must set securityContext.runAsNonRoot=true), seccompProfile (pod or container "shell" must set securityContext.seccompProfile.type to "RuntimeDefault" or "Localhost")
Check:The namespace objects are created and the privileged pod is
Forbidden. -
5A workload that passes the restricted policy
What a compliant pod looks like: runs as a non-root user ID, the default seccomp profile, no privilege escalation, all capabilities dropped, a read-only root filesystem, and no service account token mounted because it doesn't call the Kubernetes API. The app listens on 8080 because non-root processes shouldn't need port 80.
app.yaml apiVersion: apps/v1 kind: Deployment metadata: name: web namespace: shop-prod spec: replicas: 2 selector: matchLabels: app: web template: metadata: labels: app: web spec: automountServiceAccountToken: false securityContext: runAsNonRoot: true runAsUser: 10001 seccompProfile: type: RuntimeDefault containers: - name: whoami image: traefik/whoami:v1.11.0 args: ["--port", "8080"] ports: - name: http containerPort: 8080 securityContext: allowPrivilegeEscalation: false readOnlyRootFilesystem: true capabilities: drop: ["ALL"] readinessProbe: httpGet: path: /health port: http resources: requests: cpu: 50m memory: 32Mi limits: memory: 64Mi --- apiVersion: v1 kind: Service metadata: name: web namespace: shop-prod spec: selector: app: web ports: - name: http port: 80 targetPort: http -
6Deploy it and read the quota
Run kubectl apply -f app.yaml kubectl -n shop-prod rollout status deployment/web kubectl -n shop-prod describe resourcequota shop-prodExpected output
deployment.apps/web created service/web created Waiting for deployment "web" rollout to finish: 0 of 2 updated replicas are available... Waiting for deployment "web" rollout to finish: 1 of 2 updated replicas are available... deployment "web" successfully rolled out Name: shop-prod Namespace: shop-prod Resource Used Hard -------- ---- ---- limits.memory 128Mi 4Gi pods 2 20 requests.cpu 100m 2 requests.memory 64Mi 2Gi services.loadbalancers 0 0
Check:Two pods running, and the quota counts their requests and limits.
-
7Check what the deployer may do
kubectl auth can-i --asasks the API server's own authorizer, so it is the reliable way to test RBAC.Run SA=system:serviceaccount:shop-prod:deployer kubectl auth can-i update deployments -n shop-prod --as=$SA kubectl auth can-i get secrets -n shop-prod --as=$SA kubectl auth can-i delete namespaces --as=$SA kubectl auth can-i update deployments -n kube-system --as=$SAExpected output
yes no Warning: resource 'namespaces' is not namespace scoped no no
-
8Without network policy, anyone can connect
By default every pod can reach every other pod in the cluster. A pod in the
defaultnamespace reaches the app:Run kubectl -n default run np-test --rm -i --restart=Never --image=busybox:1.38.0 -- wget -qO- -T 3 http://web.shop-prodExpected output
Hostname: web-56bcd9dc9-txcqx ... pod "np-test" deleted from default namespace
-
9Default deny, then allow exactly one path
NetworkPolicies are allow-lists. The first policy selects every pod in
shop-prodand allows no incoming traffic. The second allows connections to the web pods on port 8080, only from pods in theedgenamespace (where a gateway would run). The CNI plugin enforces them; kind's kindnet does, as do the cloud CNIs with policy enabled.NetworkPolicy: deny everything, then allow exactly what you need networkpolicies.yaml # 1. Nothing may connect to pods in shop-prod... apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: default-deny-ingress namespace: shop-prod spec: podSelector: {} policyTypes: ["Ingress"] --- # 2. ...except pods in the "edge" namespace (where the gateway runs), and only on the app port. apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: allow-web-from-edge namespace: shop-prod spec: podSelector: matchLabels: app: web policyTypes: ["Ingress"] ingress: - from: - namespaceSelector: matchLabels: kubernetes.io/metadata.name: edge ports: - protocol: TCP port: 8080 -
10Test from both namespaces
Run kubectl apply -f networkpolicies.yaml kubectl create namespace edge kubectl -n default run np-test --rm -i --restart=Never --image=busybox:1.38.0 -- wget -qO- -T 3 http://web.shop-prod kubectl -n edge run np-test --rm -i --restart=Never --image=busybox:1.38.0 -- wget -qO- -T 3 http://web.shop-prodExpected output
networkpolicy.networking.k8s.io/default-deny-ingress created networkpolicy.networking.k8s.io/allow-web-from-edge created namespace/edge created wget: download timed out pod "np-test" deleted from default namespace pod default/np-test terminated (Error) Hostname: web-56bcd9dc9-txcqx pod "np-test" deleted from edge namespace
Check:defaulttimes out;edgegets an answer.Hint
Policies also cover outgoing traffic (
policyTypes: [Egress]). If you add egress rules, remember to allow DNS (UDP and TCP 53 to kube-system) or every lookup fails. -
11Install Argo CD
Argo CD runs in its own namespace: the repo-server fetches and renders manifests (plain YAML, Kustomize, Helm), the application-controller compares them with the cluster and syncs, the server provides the UI and API, and redis caches state.
--server-sideis needed for its large CRDs.Run kubectl create namespace argocd kubectl apply -n argocd --server-side --force-conflicts -f https://raw.githubusercontent.com/argoproj/argo-cd/v3.6.3/manifests/install.yaml kubectl -n argocd wait deployment --all --for=condition=Available --timeout=5m kubectl -n argocd get podsExpected output
namespace/argocd created ... networkpolicy.networking.k8s.io/argocd-server-network-policy serverside-applied deployment.apps/argocd-applicationset-controller condition met deployment.apps/argocd-dex-server condition met deployment.apps/argocd-notifications-controller condition met deployment.apps/argocd-redis condition met deployment.apps/argocd-repo-server condition met deployment.apps/argocd-server condition met NAME READY STATUS RESTARTS AGE argocd-application-controller-0 1/1 Running 0 39s argocd-applicationset-controller-56846db5fb-2pzlv 1/1 Running 0 39s argocd-dex-server-5fd759dd9-rp552 1/1 Running 0 39s argocd-notifications-controller-84cb67fc5d-67dnt 1/1 Running 0 39s argocd-redis-86d4d669f7-97mck 1/1 Running 0 39s argocd-repo-server-966c64566-qpdhz 1/1 Running 0 39s argocd-server-677c666df4-hg9wh 1/1 Running 0 39s
-
12Describe an app as an Argo CD Application
An Application says: keep this namespace equal to this path of this Git repository.
automatedsyncs without a human clicking;prunedeletes what was removed from Git;selfHealreverts changes made in the cluster. This one uses Argo CD's public example repository so it works without setting up your own.argocd/guestbook-app.yaml # Argo CD keeps the guestbook namespace identical to the guestbook folder of a Git repository. apiVersion: argoproj.io/v1alpha1 kind: Application metadata: name: guestbook namespace: argocd spec: project: default source: repoURL: https://github.com/argoproj/argocd-example-apps.git targetRevision: master path: guestbook destination: server: https://kubernetes.default.svc namespace: guestbook syncPolicy: automated: prune: true # delete what was removed from Git selfHeal: true # undo changes made by hand in the cluster syncOptions: - CreateNamespace=true -
13Let Argo CD deploy it
Run kubectl apply -f argocd/guestbook-app.yaml # wait about 20 seconds kubectl -n argocd get application guestbook kubectl -n guestbook get deployments,servicesExpected output
application.argoproj.io/guestbook created NAME SYNC STATUS HEALTH STATUS guestbook Synced Healthy NAME READY UP-TO-DATE AVAILABLE AGE deployment.apps/guestbook-ui 1/1 1 1 13s NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE service/guestbook-ui ClusterIP 10.96.7.88 <none> 80/TCP 13s
Check:Synced(the cluster matches Git) andHealthy(the resources are working). You never rankubectl applyon the app itself. -
14Make a manual change and watch it get undone
Someone scales the app by hand. Within seconds Argo CD sees the cluster differs from Git and puts it back. This is what makes production predictable: the only lasting changes are the ones in Git.
Run kubectl -n guestbook scale deployment/guestbook-ui --replicas=4 for i in 1 2 3 4 5 6; do kubectl -n guestbook get deployment guestbook-ui --no-headers; sleep 2; done kubectl -n argocd get application guestbook -o jsonpath='{.status.operationState.message}{"\n"}' kubectl -n argocd get application guestbook -o jsonpath='{range .status.history[*]}{.id} {.revision} {.deployedAt}{"\n"}{end}'Expected output
deployment.apps/guestbook-ui scaled guestbook-ui 1/4 4 1 20s guestbook-ui 1/1 1 1 22s guestbook-ui 1/1 1 1 24s guestbook-ui 1/1 1 1 26s guestbook-ui 1/1 1 1 28s guestbook-ui 1/1 1 1 30s successfully synced (all tasks run) 0 8088f4c0d970abb09e250248cc97e35623447cb5 2026-11-26T19:33:55Z
Check:Back to 1 replica within seconds, and the history records the Git commit that is deployed.
-
15Point Argo CD at your own repository
Push the
shop-k8sfolder from lab 5 to a repository you own and replaceYOUR-ORG. Argo CD rendersoverlays/prodwith Kustomize and keepsshop-prodin sync. Private repositories need a read-only deploy key or token registered with Argo CD (argocd repo add).argocd/shop-prod-app.yaml # Your own app: Argo CD renders overlays/prod from your repository (lab 5) and keeps shop-prod in sync. apiVersion: argoproj.io/v1alpha1 kind: Application metadata: name: shop-prod namespace: argocd spec: project: default source: repoURL: https://github.com/YOUR-ORG/shop-k8s.git targetRevision: main path: overlays/prod destination: server: https://kubernetes.default.svc namespace: shop-prod syncPolicy: automated: prune: true selfHeal: true syncOptions: - CreateNamespace=true -
16Validate, then hand it to Argo CD
A server-side dry run checks the Application against the installed CRD without creating it.
Run kubectl apply --dry-run=server -f argocd/shop-prod-app.yaml kubectl apply -f argocd/shop-prod-app.yaml kubectl -n argocd get application shop-prodExpected output
application.argoproj.io/shop-prod created (server dry run)
Check:Once your repository is reachable, the Application reaches
Synced. It reportsDegradedor sync errors if a resource is rejected; see the hint.Hint
This Application deploys into
shop-prod, which enforces Pod Securityrestricted. The lab 5 base runs whoami on port 80 as root, so admission rejects its pods until you add the security settings fromapp.yamlto the base. That's the policy doing its job.
Clean up
Remove the applications first so Argo CD stops syncing, then the namespaces, then the whole kind cluster:
kubectl delete -f argocd/guestbook-app.yaml
kubectl delete namespace guestbook shop-prod edge argocd
kind delete cluster --name lab-k8s-local
kind get clusters should print No kind clusters found., and docker ps should show no lab-k8s-local-…
containers.
In production
Everything in this lab is what a production platform team sets up once and applies to every namespace and cluster. The difference in real production is scale, automation and the operational practices around it.
What changes
| In this lab | In production |
|---|---|
| Guardrails applied by hand to one namespace | A namespace template (or a policy engine such as Kyverno or Gatekeeper) applied to every team namespace by GitOps |
| One example app in Argo CD | An app-of-apps or ApplicationSet per environment; Argo CD itself managed from Git, with SSO and its own RBAC |
| Public example repository | Your repositories, read-only credentials, signed commits, branch protection and required reviews |
kubectl delete to clean up |
Removal is a pull request; prune deletes resources that leave Git |
| No monitoring | Prometheus (or a managed equivalent) for metrics, a log pipeline, alerts on SLOs, error budgets |
| No backups | Velero (or the cloud's backup) for cluster objects and volumes, restores tested regularly |
| One cluster | Separate clusters per environment (often per region), upgraded in order: dev, staging, prod |
Observability
Collect the golden signals (latency, traffic, errors, saturation) per service, plus cluster signals: node
pressure, pending pods, restarts, OOMKills, HPA at maximum, certificate expiry, and Argo CD apps that are
OutOfSync or Degraded. Alert on symptoms users feel, and keep runbooks next to the alerts.
Upgrades and backups
Kubernetes ships three minor versions a year and supports each for about 14 months. Plan an upgrade at least every six months: read the deprecation notes, upgrade dev first, then staging, then prod; upgrade add-ons (CNI, CoreDNS, gateways, Argo CD) with it. Back up cluster state and volumes, and practise restoring into an empty cluster: GitOps makes rebuilding the cluster objects fast, but data still needs backups.
Multi-cluster and environments
Keep production in its own cluster (and cloud account), with no human write access by default. Promote changes through environments by merging the same change into each overlay. For several regions, run one Argo CD per environment (or a central one with clusters registered) and an ApplicationSet that generates one Application per cluster.
Production checklist
- Every namespace has Pod Security
restricted, a ResourceQuota, a LimitRange and default-deny NetworkPolicies - People and CI have least-privilege RBAC; nobody uses cluster-admin day to day
- Production changes only through Git and GitOps, with selfHeal and prune on
- Images are scanned, signed and pinned; admission policy rejects anything else
- Secrets come from a secret manager, never from Git
- Metrics, logs and alerts on golden signals and cluster health, with runbooks
- Backups of cluster state and volumes, with tested restores
- A written upgrade plan and calendar; each version upgraded in dev first
Learn the concepts
- RBAC: Who Can Do What · Kubernetes Tutorial
- Network Policies · Kubernetes Tutorial
- Packaging with Helm and Kustomize · Kubernetes Tutorial
- Helm, Kustomize and GitOps with Argo CD · Course
- Kubernetes in Production · Course
Preparing for the CKA or CKS exam? Practice tests and mock exams →