K8sCalc

kubernetes

Kubernetes Network Policy Generator

Generate Kubernetes NetworkPolicy YAML with default-deny and allow rules for namespace isolation. Supports ingress allow-lists, egress port rules, DNS, and Prometheus scraping.

Kubernetes Network Policy Best Practices

NetworkPolicies are the primary way to implement network segmentation in Kubernetes. They operate at the pod level and use label selectors to define which traffic is allowed.

Default Deny + Allowlist

The recommended pattern:

  1. 1.Apply a default-deny policy (blocks everything)
  2. 2.Add specific allow rules for what the namespace needs

This is more secure than a default-allow model and makes the security posture explicit.

CNI Support Matrix

CNINetworkPolicy support
Flannel❌ No enforcement
Calico✅ Full
Cilium✅ Full + L7 (HTTP/gRPC aware)
Weave Net✅ Full

Namespace Label Requirement

NetworkPolicies using namespaceSelector match on namespace labels. The label kubernetes.io/metadata.name is automatically set by Kubernetes 1.21+ (it equals the namespace name). For older clusters, you must manually label namespaces:

bash
kubectl label namespace monitoring kubernetes.io/metadata.name=monitoring

Common Gotchas

  • Forgetting DNS (port 53) — breaks all service discovery
  • Missing metrics port for Prometheus — monitoring stops working silently
  • Using podSelector: {} in ingress rules — means "allow from all pods in this namespace"
  • Not allowing egress to the API server — breaks service accounts that call the K8s API

Frequently Asked Questions

What does default-deny mean in Kubernetes NetworkPolicy?

By default, Kubernetes allows all pod-to-pod traffic within a cluster. A default-deny NetworkPolicy (podSelector: {} with no ingress/egress rules) blocks all traffic to/from pods in that namespace. You then add explicit allow rules for what you need.

Do NetworkPolicies work without a CNI that supports them?

No. NetworkPolicies are API objects but enforcement is done by the CNI plugin. Flannel does NOT enforce NetworkPolicies. You need Calico, Cilium, or Weave Net for enforcement. If you use Flannel, NetworkPolicies exist but are silently ignored.

Why do I need to allow port 53 for DNS?

Kubernetes DNS (CoreDNS) listens on port 53 UDP/TCP. When pods make service calls like http://my-service.my-namespace.svc.cluster.local, they resolve via CoreDNS. Without allowing port 53 in your egress rules, all service discovery fails.

How does Prometheus scraping work with NetworkPolicies?

Prometheus in the monitoring namespace needs to reach your app's metrics endpoint (typically :8080/metrics or :9090). If your namespace has a default-deny policy, you must explicitly allow ingress from the monitoring namespace on the metrics port. The generated policy adds this as an optional rule.