Kubernetes Network Policies: Controlling Pod Traffic and Security
The pod is running, but traffic is silent. Nothing can reach it. Nothing leaves. This is the moment Kubernetes Network Policies take control.
Kubernetes Network Policies define how pods communicate with each other and with the outside world. They are a core security boundary in a cluster. Without them, every pod can talk to every other pod. With them, you decide exactly who can speak, and on which ports.
A NetworkPolicy resource in Kubernetes is written in YAML and tied to a namespace. It uses label selectors to match pods and define ingress and egress rules.
Key fields include:
- podSelector: selects the pods the policy applies to.
- policyTypes: ingress, egress, or both.
- ingress and egress: define allowed traffic sources and destinations.
Example:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: restrict-web
namespace: production
spec:
podSelector:
matchLabels:
app: web
policyTypes:
- Ingress
ingress:
- from:
- podSelector:
matchLabels:
role: backend
ports:
- protocol: TCP
port: 80
This policy allows only pods labeled role: backend to connect to the web app on port 80. All other incoming traffic is blocked.
For a tty context—like when you exec into a pod’s shell—network policies still control connectivity. A kubectl exec -it with a TTY gives you an interactive session inside a container, but it doesn’t bypass policy rules. If egress is blocked, your shell inside the pod will fail to reach forbidden endpoints. If ingress is restricted, external processes can’t connect to services in your session.
To test policies, create isolated namespaces and deploy simple server and client pods. Attach labels with precision. Apply network policies incrementally and confirm rules with kubectl exec -it commands and network tools like curl or nc. Keep egress deny-all defaults for high-security workloads, then add explicit allow rules.
Kubernetes applies policies only if a network plugin supports them, such as Calico, Cilium, or Weave Net. Without such a plugin, policies have no effect. Always verify your CNI is policy-aware before relying on configuration.
Misconfigured policies can break services fast. Always version them in Git, review changes, and roll out progressively. Combine them with RBAC, pod security standards, and TLS to lock down your cluster traffic from multiple angles.
Want a place to design, apply, and test Kubernetes Network Policies with TTY access before touching production? Try it live in minutes on hoop.dev.