Network Policy Enforcement

Production-grade guide to network policy enforcement covering architecture patterns, implementation strategies, testing approaches, and operational best practices for enterprise engineering teams.

Network policy enforcement is the practice of programmatically defining and guaranteeing that traffic between workloads adheres to a security intent. In a devsecops context it matters when you are hardening a cluster, implementing zero‑trust boundaries, preventing lateral movement, or meeting compliance requirements that mandate segmented communication paths. Unlike firewall rules that operate at the host or perimeter level, network policy enforcement occurs at the orchestration layer, attaching constraints to pods, namespaces, or their labels. The enforcement point is the CNI plugin; if the plugin does not implement (or support) the Kubernetes NetworkPolicy API, policies are silently ignored and no enforcement occurs.

The following sections are organized around the tasks a reader is likely to perform, with concrete commands, real configuration keys, and the exact failure modes you encounter when policy logic diverges from intent.

1 Define & Apply a Network Policy

The canonical way to describe intent is a NetworkPolicy resource natively supported by the Kubernetes API. Below is a minimal policy that allows ingress from pods with the label app: frontend into pods with the label app: backend on port 443/tcp.

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-frontend-to-backend
  namespace: production
spec:
  podSelector:
    matchLabels:
      app: backend
  ingress:
    - from:
        - podSelector:
            matchLabels:
              app: frontend
      ports:
        - protocol: TCP
          port: 443

Apply it with the standard CLI:

kubectl apply -f allow-frontend-to-backend.yaml

If the file is syntactically valid but violates a cluster‑wide constraint, kubectl returns a concrete validation error. For example, omitting the namespace on a namespaced resource while the API server is configured with admission webhooks that enforce namespace scoping yields:

Error: networkpolicy.networking.k8s.io "allow-frontend-to-backend" is invalid: spec.ingress[0].from[0].namespace: Forbidden: must be nil for a non-namespaced resource or must be specified by namespace

A common operational mistake is forgetting that the podSelector under spec.ingress[].from selects *peer* pods, not the target pod itself; the target is already selected by spec.podSelector.matchLabels. Reverse the two and the policy either fails validation or silently permits no traffic because the selector never matches.

2 Verify Enforcement is Active

After applying a policy, the next question is “is it being enforced?” The most direct inspection command is:

kubectl describe networkpolicy allow-frontend-to-backend -n production

The output includes a Selector field, the list of From and To matchers, and, if the underlying CNI exposes it, the Endpoints or SatisfiedBy status. If the CNI implements the status subresource, you will see Status: Allowed or Denied attached to pod events.

A faster, list‑oriented check:

kubectl get networkpolicy --all-namespaces -o wide

displays the NAME, AGE, and the namespace‑level NetworkPolicy status. Absent any output, or a STATUS column that reads None, indicates one of two things: either no policy exists in those namespaces, or the CNI does not report status.

To test enforcement end‑to‑end, spin two pods with the appropriate labels and attempt connectivity. From a frontend pod:

kubectl exec -it <frontend-pod> -n production -- curl -s -o /dev/null -w "%{http_code}" https://<backend-pod-ip>:443

If the CNI enforces the policy, the connection fails with a timeout or reset. If it succeeds, either the CNI does not enforce NetworkPolicy, or the policy is not matching the actual pod labels.

3 Troubleshoot Silent Failures (Sharp Edges)

Default‑allow vs. default‑deny

By default, if no NetworkPolicy exists in a namespace, all ingress and egress is allowed. Creating any ingress policy switches the default to *deny* for ingress unless explicitly allowed; creating any egress policy switches the default to *deny* for egress unless explicitly allowed. This inversion is the single most frequent source of “suddenly no pod can talk” incidents. The remedy is to ensure every traffic path you need is explicitly listed in at least one policy, or to retain a catch‑all policy at the top of the list.

CNI dependency

The Kubernetes API for NetworkPolicy is standard, but enforcement is entirely downstream of the CNI. kube-router, calico, cilium, and kubenet (with --networkpolicy flag) all implement it, but they differ in performance, feature parity, and status reporting. If kubectl describe networkpolicy shows no Status field and kubectl exec connectivity tests ignore the policy, first confirm which CNI is running:

kubectl get nodes -o wide | head -1
# then inspect /etc/cni/net.d/ or run `ps aux | grep kubelet` / `crictl info`

A mismatched or disabled CNI will silently drop the policy logic.

Label‑matching gotchas

podSelector.matchLabels performs an *and* across keys, and an *or* across policy rules. A frequent misconfiguration is writing:

ingress:
  - from:
      - podSelector:
          matchLabels:
            app: frontend
            tier: web

expecting any pod labeled app: frontend *or* tier: web to be allowed. In reality, only pods matching both labels are permitted. To allow either label, write two separate ingress entries.

Rule ordering

NetworkPolicy rules are evaluated top‑to‑bottom, first‑match wins. If you have a broad allow rule followed by a narrow deny, the deny never fires. Conversely, a deny rule at the top can starve subsequent allows. Always place the most specific rules first, or use a dedicated “catch‑all” policy at the bottom with an explicit allow if you need a fallback.

Silent‑fail CNI misconfiguration

Even with a correctly written policy, the CNI may log nothing and enforce nothing if its own configuration is broken. In Calico, for example, felix enabled must be true and nodeolidr must match the node’s CIDR. In Cilium, the BPF program may fail to attach if the kernel lacks required capabilities, producing no user‑visible error but silently allowing all traffic. When in doubt, cordon the node, restart the CNI pod, and re‑apply the policy while watching kubectl get events --field-selector involvedObject.kind=NetworkPolicy.

4 Configure Selective Ingress/Egress

Ingress with namespace scoping

To restrict a policy to a single namespace while allowing cross‑namespace peers:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: cross-ns-ingress
  namespace: staging
spec:
  podSelector:
    matchLabels:
      app: api
  ingress:
    - from:
        - namespaceSelector:
            matchLabels:
              name: production
          podSelector:
            matchLabels:
              app: frontend
      ports:
        - protocol: TCP
          port: 80

The namespaceSelector.matchLabels key must be present and match the namespace of the allowed peer pods. Omitting it defaults to “all namespaces,” which, combined with an ingress policy, enforces *deny‑by‑default* for ingress from other namespaces.

Egress with port‑level granularity

Egress policies are frequently used to restrict outbound traffic to specific domains or IP ranges. The Kubernetes API itself does not carry CIDR or FQDN matching; that is a CNI extension. However, the core API supports port/protocol restrictions. Example:

spec:
  egress:
    - to:
        - podSelector:
            matchLabels:
              app: external-service
      ports:
        - protocol: TCP
          port: 443
        - protocol: UDP
          port: 53

If you need FQDN or CIDR egress, you must use a CNI‑specific CRD (Calico’s networkpolicy with ipBlock, Cilium’s L7 rules, etc.). The core API will reject unknown fields during validation, returning:

Error: networkpolicy.networking.k8s.io "egress-example" is invalid: spec.egress[0].to[0].cidr: Unknown field "cidr" in networking.k8s.io/v1

Common port‑protocol confusion

A frequent error is swapping port and port. The field port is a single integer or range; ports is a array of port protocol objects. Omitting protocol defaults to TCP, which can silently allow traffic you intended to restrict to UDP or SCTP. Always declare protocol explicitly when the service is not strictly TCP.

5 Integrate into CI/CD or Automation

Policies live in version control just like any other infrastructure-as-code artifact. A typical CI step validates the YAML before it reaches the cluster:

# install kubeval or kubeconform once
curl -sL https://github.com/instrumenta/kubeval/releases/download/v0.16.1/kubeval-linux-amd64.tar.gz | tar -xz -C /tmp
# validate
/tmp/kubeval allow-frontend-to-backend.yaml

If the file passes schema validation, kubectl apply -f is invoked in the apply job. A downstream gate can kubectl get networkpolicy and assert expected fields exist, catching drift early.

Automation also benefits from policy‑generation templates. A small script can scaffold a policy from a CSV of allowed services, injecting the correct matchLabels and port values, then kubectl apply -f -. Because the generated YAML adheres to the standard networking.k8s.io/v1 schema, it is portable across any CNI that implements the API.

Gotchas Recap

Understanding these mechanics, wielding the exact kubectl and YAML tools, and anticipating the silent‑fail paths will let you enforce network boundaries that are both precise and resilient.

This page was rewritten on 12 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.