How to Deny All Traffic Using Network Policy in Kubernetes
To deny all traffic in Kubernetes, create a
NetworkPolicy with an empty podSelector and no ingress or egress rules. This blocks all incoming and outgoing traffic to pods in the namespace where the policy is applied.Syntax
A NetworkPolicy resource defines rules to allow or deny traffic to pods. To deny all traffic, you create a policy with an empty podSelector that selects all pods, and omit ingress and egress rules. This means no traffic is allowed in or out.
- apiVersion: Kubernetes API version for network policies.
- kind: Must be
NetworkPolicy. - metadata.name: Name of the policy.
- spec.podSelector: Selects pods this policy applies to; empty means all pods.
- spec.policyTypes: Specifies if the policy applies to
Ingress,Egress, or both. - spec.ingress and spec.egress: Lists of allowed traffic rules; empty or missing means deny all.
yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: deny-all
spec:
podSelector: {}
policyTypes:
- Ingress
- EgressExample
This example creates a NetworkPolicy named deny-all that denies all ingress and egress traffic to all pods in the namespace. No pods can send or receive network traffic until other policies allow it.
yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: deny-all
spec:
podSelector: {}
policyTypes:
- Ingress
- EgressOutput
networkpolicy.networking.k8s.io/deny-all created
Common Pitfalls
Common mistakes when denying all traffic with NetworkPolicy include:
- Not specifying
policyTypesfor bothIngressandEgress, which may only block one direction. - Using a non-empty
podSelectorthat selects no pods, so the policy does not apply. - Expecting the policy to apply across namespaces; NetworkPolicies are namespace-scoped.
- Forgetting that once a NetworkPolicy exists, pods without explicit allow rules are isolated.
yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: wrong-deny-all
spec:
podSelector: {}
policyTypes:
- Ingress
# Missing Egress means egress traffic is allowed
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: correct-deny-all
spec:
podSelector: {}
policyTypes:
- Ingress
- EgressQuick Reference
Summary tips for denying all traffic with Kubernetes NetworkPolicy:
- Use an empty
podSelector: {}to select all pods. - Specify both
IngressandEgressinpolicyTypesto block all directions. - Do not add any
ingressoregressrules to deny all traffic. - Remember NetworkPolicies are namespace-scoped.
Key Takeaways
Create a NetworkPolicy with empty podSelector and no ingress or egress rules to deny all traffic.
Specify both Ingress and Egress in policyTypes to block all incoming and outgoing traffic.
NetworkPolicies apply only within their namespace; cross-namespace traffic requires separate policies.
Once a NetworkPolicy exists, pods are isolated by default unless allowed by rules.
Always test policies in a safe environment to avoid accidental service disruption.