A NetworkPolicy selects Pods and states which layer-four ingress or egress connections are allowed. It works only when the cluster network implementation enforces it. A policy is additive: multiple policies selecting a Pod combine allowed traffic. It does not inspect HTTP paths or replace application authentication.
Kubernetes NetworkPolicy: permit only required flows
Operational decision
For a claims API, begin with a namespace isolation plan and list the flows the service actually needs: ingress from the gateway, DNS queries, database access, and telemetry egress. Apply an ingress policy to one canary namespace and test both allowed and denied connections before broad rollout. The sample allows TCP port 8080 from Pods labelled role=gateway in the same namespace. It says nothing about egress and does not provide a global default deny; add separate rules after mapping outbound needs. A namespace selector is needed for cross-namespace sources. Before relying on any deny test, verify that the CNI implements NetworkPolicy. Record the observed denied path, because a broken DNS egress rule can look like application failure.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: {name: claims-api-ingress}
spec:
podSelector: {matchLabels: {app: claims-api}}
policyTypes: [Ingress]
ingress:
- from:
- podSelector: {matchLabels: {role: gateway}}
ports:
- {protocol: TCP, port: 8080}Cost and verification
Policies add review and testing cost. A deny-by-default rollout can cut off DNS, health checks, metrics, or control traffic if the flow inventory is incomplete. The shown peer selector matches Pods in the policy's namespace; it does not permit an identically labelled Pod elsewhere. Kubernetes NetworkPolicy handles TCP and UDP, with SCTP support depending on the implementation; other protocols have implementation-specific behavior. Test the exact cluster plugin rather than treating a manifest accepted by the API as enforced security.
Common Mistakes
- Do not assume policy enforcement from API acceptance alone.
- Do not forget DNS and telemetry egress during isolation.
- Do not treat a same-namespace podSelector as a cross-namespace rule.
Connected lessons
- DevOps: delivery, infrastructure, and reliable operations
- Kubernetes Service discovery: selectors, endpoints, and DNS
- Kubernetes RBAC: bind one service account to one job
- Secrets and configuration across the delivery path
