0 / 15 lessons — 0%
Lesson 15 / 15 ✅

NetworkPolicies & init containers

Last stop: locking down which pods can talk to which, and making sure setup work finishes before your app's main container ever starts.

NetworkPolicies — a firewall between pods

By default, every pod in a cluster can reach every other pod — flat, open networking. A NetworkPolicy restricts that, allow-listing traffic by label selector instead of leaving everything wide open. The moment a NetworkPolicy selects a pod, that pod's traffic is default-deny except for what the policy explicitly allows.

# networkpolicy.yaml — only pods labeled app: web may reach the db pods, on port 5432 apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: db-allow-web-only spec: podSelector: matchLabels: app: db policyTypes: ["Ingress"] ingress: - from: - podSelector: matchLabels: app: web ports: - protocol: TCP port: 5432
Requires a CNI plugin that supports it. NetworkPolicy objects are inert on some basic network setups — Calico, Cilium, and most managed cloud CNIs support them, but check before assuming a policy is actually being enforced.

Init containers — setup before the real thing starts

An init container runs to completion before any of a Pod's regular containers start — perfect for "wait until the database is reachable" or "run a quick migration" without baking that logic into the app image itself.

spec: initContainers: - name: wait-for-db image: busybox command: ["sh", "-c", "until nc -z db 5432; do sleep 2; done"] containers: - name: web image: myregistry/web:1.5.0

If an init container fails, Kubernetes retries it — the main containers simply never start until every init container in the list has succeeded, in order.

Try it yourselfAdd the wait-for-db init container above to a Deployment and apply it before its database exists. Run kubectl get pods — you'll see the pod sitting in Init:0/1, patiently waiting, instead of crash-looping the way it would without one.
That's the gap closed. Between the first 11 lessons and these 4, you've now got StatefulSets, Jobs/CronJobs, DaemonSets, RBAC, Namespaces, autoscaling, scheduling control, NetworkPolicies, and init containers — genuinely the concepts that come up in real clusters and in interviews. Take the quiz, then Ansible is next.