⌂ Home

Kubernetes Network Policies

Control pod-to-pod, namespace, and external traffic with ingress and egress rules

What are NetworkPolicies?

Repository YAML files: Ready-to-use NetworkPolicy manifests are available in k8s/labs/security/:
  • deny-all-ingress.yaml — Deny all ingress to pods labeled app: k8slearning
  • allow-ingress.yaml — Allow ingress only from pods with matching app: k8slearning label
  • deny-from-other-namespaces.yaml — Deny cross-namespace ingress in the prod namespace

NetworkPolicies are Kubernetes resources that express Layer 3 / Layer 4 rules (IP, ports, protocols) for which traffic may reach your Pods. Think of them as a distributed firewall: the CNI plugin enforces the rules on the data plane.

Default cluster behavior

If no NetworkPolicy selects a Pod, all traffic is allowed in both directions. The cluster is “open” until you opt in to restrictions.

Implicit deny when a Pod is selected

As soon as any NetworkPolicy’s podSelector matches a Pod, that Pod is now governed by NetworkPolicy semantics for the directions listed in policyTypes. Traffic that does not match an explicit allow rule is dropped for those directions.

Key idea: Policies are allow lists. Unlisted flows are denied once the Pod participates in policy evaluation for ingress and/or egress.

Three selector dimensions

Ingress vs egress

CNI support

NetworkPolicy requires a CNI that implements it. Examples: Calico, Cilium, Weave Net (and many managed CNIs). Flannel alone does not enforce NetworkPolicy unless paired with another controller (for example Calico for policy). Always verify your platform’s docs.

Before and after (visual)

Before any policy

Pod A Pod B Pod C Every pod can reach every pod (typical default).

After policy on Pod B

Pod A Pod B Pod C Only flows matching your allow rules reach B; others are dropped.