yaml 28 lines · 1 tab

Kubernetes NetworkPolicy for namespace level traffic control

Kai Nakamura Apr 2026
1 tab
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: api-ingress
  namespace: production
spec:
  podSelector:
    matchLabels:
      app: api
  policyTypes:
    - Ingress
    - Egress
  ingress:
    - from:
        - namespaceSelector:
            matchLabels:
              name: ingress-nginx
      ports:
        - protocol: TCP
          port: 3000
  egress:
    - to:
        - podSelector:
            matchLabels:
              app: postgres
      ports:
        - protocol: TCP
          port: 5432
1 file · yaml Explain with highlit

Cluster flat networking is convenient right up until an attacker lands in one pod. I define NetworkPolicy resources early so east-west communication is explicit, reviewable, and least-privilege by default. This makes later incident containment far more realistic.

Share this code

Here's the card — post it anywhere.

Kubernetes NetworkPolicy for namespace level traffic control — share card
Link copied