K8s NetworkPolicy

Kubernetes NetworkPolicy YAML Security Rule Generator

Create fine-grained Kubernetes NetworkPolicy YAML manifests with Ingress/Egress CIDR blocks, podSelector labels, namespaceSelector, and port restrictions.

Presets:
Enforced Policy Types (spec.policyTypes)
Target Pods Selector (spec.podSelector)

Define which pods inside namespace "production" this security policy restricts.

Match Labels (key = value):
=
=
Policy Metadata Labels
:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: backend-api-netpol
  namespace: production
  labels:
    tier: api
spec:
  podSelector:
    matchLabels:
      app: backend-api
      tier: api
  policyTypes:
    - Ingress
    - Egress
  ingress:
    - # Allow HTTP from Frontend Pods
      from:
        - podSelector:
            matchLabels:
              app: web-frontend
      ports:
        - protocol: TCP
          port: 8080
    - # Allow Metrics Scraping from Monitoring Namespace
      from:
        - namespaceSelector:
            matchLabels:
              kubernetes.io/metadata.name: monitoring
          podSelector:
            matchLabels:
              app: prometheus
      ports:
        - protocol: TCP
          port: 9090
  egress:
    - # Allow CoreDNS Resolution in kube-system
      to:
        - namespaceSelector:
            matchLabels:
              kubernetes.io/metadata.name: kube-system
          podSelector:
            matchLabels:
              k8s-app: kube-dns
      ports:
        - protocol: UDP
          port: 53
        - protocol: TCP
          port: 53
    - # Allow PostgreSQL Connection
      to:
        - podSelector:
            matchLabels:
              app: postgres
      ports:
        - protocol: TCP
          port: 5432
    - # Allow Redis Cluster Egress
      to:
        - podSelector:
            matchLabels:
              app: redis
      ports:
        - protocol: TCP
          port: 6379
Target Pods
2 Label Selectors
Active Rules
2 Ingress • 3 Egress (6 Ports)
Security Posture
100% Zero-Trust Compliant

Zero-Trust Microsegmentation

Generate RFC-compliant Kubernetes networking policies with precise podSelector, CIDR blocks, and port whitelisting.

100% In-Browser Privacy

All policy configurations, IP subnets, and cluster topology remain strictly in your browser memory with zero network calls.

Production GitOps Delivery

Instantly exports standard Kubernetes manifests alongside parameterized Helm templates and Kustomize overlays.

Technical Reference & Architecture Guide

Kubernetes NetworkPolicy Generator — Reference Guide

Production-grade reference for generating declarative Kubernetes NetworkPolicy manifests, zero-trust pod isolation, namespace ingress/egress rules, CIDR ipBlocks, and multi-port specs.

Key Parameters & Controls

metadata.namestring (RFC 1123)

Unique identifier for the NetworkPolicy resource within the namespace. Must consist of lowercase alphanumeric characters, hyphens, or periods up to 253 characters.

Default: "app-network-policy"
metadata.namespacestring (DNS Label)

Target Kubernetes namespace hosting workloads subject to policy enforcement. NetworkPolicies isolate pods only within their declared namespace boundary.

Default: "default"
spec.podSelector.matchLabelsobject (key-value)

Key-value label selectors identifying target pods. When matchAllPods is true, an empty selector {} is generated to enforce policy constraints across all pods in the namespace.

Default: {"app": "backend"}
spec.policyTypesstring[] (Ingress | Egress)

Specifies active policy enforcement directions. Omitting a direction leaves that traffic unrestricted, while declaring a type without corresponding rules acts as an explicit default-deny.

Default: ["Ingress"]
spec.ingress[*].from[*]array of PeerEntry

Whitelisted ingress traffic origins. Supports podSelector, namespaceSelector, combined pod-and-namespace selectors (logical AND), or ipBlock CIDR ranges with optional exclusion subnets.

Default: []
spec.ingress[*].ports[*]array of PortEntry

Destination network ports and layer 4 transport protocols (TCP, UDP, SCTP). Supports integer ports, named container ports, and continuous port ranges via the endPort attribute.

Default: []
spec.egress[*].to[*].ipBlockobject (cidr, except)

CIDR notation block defining external IPv4 or IPv6 subnet ranges allowed for outbound traffic, excluding internal cluster IPs or specific subnets defined in the except array.

Default: {"cidr": "0.0.0.0/0", "except": ["10.0.0.0/8"]}

Pro Tips & Best Practices

Enforce Default Deny Baseline

Deploy a namespace-wide default-deny NetworkPolicy by setting podSelector: {} with policyTypes: ['Ingress', 'Egress'] and empty rule arrays. This implements zero-trust isolation, ensuring no uninspected lateral traffic flows between workloads until explicit allow rules are committed.

Scope Cross Namespace Peers

When allowing traffic from another namespace, distinguish between separate array elements (OR logic) and a single peer object containing both namespaceSelector and podSelector (AND logic). A single combined entry restricts access strictly to targeted pods within matched namespaces rather than all pods.

Whitelist Kube DNS UDP Port 53

Whenever declaring egress policies on workloads, explicitly allow egress UDP and TCP port 53 to kube-system pods running kube-dns or CoreDNS. Omitting DNS egress breaks in-cluster service discovery, causing downstream HTTP and database connections to fail with resolution timeouts.

Utilize EndPort for Dynamic Ranges

Take advantage of the endPort field in Kubernetes 1.22+ to allow port ranges (e.g., ports 30000 to 32767 for passive FTP, WebRTC, or media streaming) within a single PortEntry instead of generating hundreds of individual port definitions.

Common Gotchas & Troubleshooting

Applied NetworkPolicy YAML has no effect and all pod communication remains completely unconstrained.

Verify that the Kubernetes cluster is running a CNI network plugin with active NetworkPolicy enforcement capabilities (such as Calico, Cilium, Weave Net, or AWS VPC CNI with amazon-network-policy-controller enabled). Default basic CNIs like Flannel or standard AWS VPC CNI without the policy controller silently ignore NetworkPolicy resources while kubectl still reports successful creation.

Workload pods lose internal service discovery and fail to resolve DNS hostnames after applying Egress rules.

When policyTypes includes 'Egress', Kubernetes disables all outbound traffic from matched pods by default. You must add an explicit Egress rule targeting namespace 'kube-system' with podSelector matching 'k8s-app: kube-dns' on UDP and TCP port 53, or create a cluster-wide DNS egress allow policy.

Combining podSelector and namespaceSelector in YAML unexpectedly permits traffic from all pods.

Ensure that 'podSelector' and 'namespaceSelector' are declared within the SAME list item block under 'from:' or 'to:'. If they are placed under separate hyphenated list items, Kubernetes treats them as a logical OR, matching all pods in the namespace AND all pods cluster-wide matching the podSelector.

Frequently Asked Questions

Which Kubernetes CNI plugins support NetworkPolicy enforcement out of the box?▼

Calico, Cilium, Kube-router, and VMware Antrea provide native NetworkPolicy enforcement out of the box. Flannel does not support NetworkPolicies unless paired with Calico (Canal). Cloud-native CNIs like AWS VPC CNI require installing the Amazon Network Policy Controller, whereas Azure CNI and GKE Dataplane V2 support NetworkPolicies when policy enforcement is enabled at cluster creation.

What is the difference between declaring an empty ingress array ([]) versus omitting the ingress field?▼

When 'Ingress' is present in policyTypes, specifying 'ingress: []' (an empty array) denies all incoming traffic to selected pods (default-deny ingress). In contrast, completely omitting the 'ingress' key or passing 'ingress: [{}]' creates an open allow-all ingress rule permitting traffic from any source. Precision in YAML structure is critical to avoid accidental traffic exposure.

Can standard Kubernetes NetworkPolicy inspect or filter Layer 7 protocols like HTTP headers or URLs?▼

No. Native Kubernetes NetworkPolicies operate strictly at Layer 3 (IP addresses and CIDR blocks) and Layer 4 (TCP, UDP, and SCTP ports). To enforce Layer 7 policies, such as path-based routing, HTTP method filtering, or mTLS authorization headers, you must use service mesh implementations like Istio, Linkerd, or Cilium Network Policies (CiliumNetworkPolicy CRDs).

Why does ipBlock fail when attempting to match the internal IP address of a pod in the cluster?▼

The Kubernetes specification explicitly states that ipBlock is designed solely for cluster-external IP ingress and egress traffic. When communicating between cluster pods, CNI plugins apply podSelector and namespaceSelector rules. Pod IPs are dynamically assigned and often translated via kube-proxy or CNI masquerading, which causes ipBlock rules targeting internal pod IPs to behave unpredictably or fail entirely.

How does the Generator produce Helm and Kustomize manifests entirely on the client side?▼

The generator executes pure TypeScript transformation functions in the browser runtime without transmitting data to external servers. It formats the reactive NetworkPolicy state into structured YAML documents, Helm templates parameterized with Release.Name and Chart.AppVersion values, and kustomization.yaml resources ready for local download or clipboard export.

Related Tools & Utilities

All Tools →