πŸ›‘ Kubernetes Network Policies Cheat Sheet

πŸ“Œ What are Network Policies?

Network Policies in Kubernetes control inbound and outbound traffic to and from pods, helping enforce security rules at the network level.

πŸ”Ή Basic Commands

  • List all network policies: sh kubectl get networkpolicy -A
  • Describe a network policy: sh kubectl describe networkpolicy <policy-name> -n <namespace>
  • Delete a network policy: sh kubectl delete networkpolicy <policy-name> -n <namespace>

πŸ”Ή Default Deny All Traffic

  • Deny all ingress and egress traffic for a namespace: ```yaml apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: deny-all namespace: default spec: podSelector: {} policyTypes:
    • Ingress
    • Egress ```

πŸ”Ή Allow All Ingress Traffic

  • Allow all inbound traffic to all pods in a namespace: ```yaml apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: allow-all-ingress namespace: default spec: podSelector: {} policyTypes:
    • Ingress ingress:
    • {} # Allow all traffic ```

πŸ”Ή Allow Only From Specific Pods

  • Allow ingress only from pods labeled role=frontend: ```yaml apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: allow-from-frontend namespace: default spec: podSelector: matchLabels: app: backend policyTypes:
    • Ingress ingress:
    • from:
    • podSelector: matchLabels: role: frontend ```

πŸ”Ή Allow Traffic Only From a Specific Namespace

  • Allow ingress only from pods in the frontend namespace: ```yaml apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: allow-from-namespace namespace: default spec: podSelector: matchLabels: app: backend policyTypes:
    • Ingress ingress:
    • from:
    • namespaceSelector: matchLabels: name: frontend ```

πŸ”Ή Restrict Egress to Specific CIDR

  • Allow egress only to 10.0.0.0/24 subnet: ```yaml apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: restrict-egress-cidr namespace: default spec: podSelector: matchLabels: app: backend policyTypes:
    • Egress egress:
    • to:
    • ipBlock: cidr: 10.0.0.0/24 ```

πŸ”Ή Allow Egress to a Specific Service

  • Allow egress to a service within the same namespace: ```yaml apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: allow-egress-to-service namespace: default spec: podSelector: matchLabels: app: backend policyTypes:
    • Egress egress:
    • to:
    • podSelector: matchLabels: app: database ```

πŸ”₯ Tips for Network Policies in Kubernetes

βœ… Network Policies are namespaced – they only apply within a single namespace.
βœ… Policies are deny-by-default when defined, unless explicitly allowing traffic.
βœ… Use kubectl exec with curl or netcat to test policy rules.
βœ… Policies only work with network plugins that support NetworkPolicy (e.g., Calico, Cilium, Weave, etc.).
βœ… Always test your policies before applying them in production!


Retour Γ  la liste