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
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.
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.