Kubernetes网络策略:全局默认拒绝与单Pod允许全部的优先级及逻辑问题
Great question—this is one of the most common gotchas when working with Kubernetes Network Policies, so let’s break this down in plain terms.
1. Which Policy Takes Priority: Default-Deny or Allow-All for a Specific Pod?
First, let’s set the baseline for how Kubernetes handles Network Policies:
- By default, Kubernetes lets all traffic flow to and from every Pod. But the second any Network Policy targets a Pod, that default switches to deny all traffic—only traffic explicitly allowed by rules will get through.
In your setup:
- You’ve got a
default-deny-allpolicy that selects every Pod (using an emptypodSelector: {}) and doesn’t define any allow rules. This puts every Pod in the "deny everything" state. - Then you add an
allow-all-for-my-podpolicy that targets one specific Pod and explicitly allows all ingress/egress traffic (via emptyingress: []andegress: []rules).
For that specific Pod, the allow-all rules will effectively override the default-deny. Here’s why:
Kubernetes checks all allow rules from every policy that targets the Pod. If any allow rule matches a traffic flow, that flow is allowed. The default-deny policy has no allow rules, but the allow-all policy has rules that match every possible flow—so all traffic to/from the Pod will be permitted.
2. AND/OR Logic for Combined Policies
The combination logic is easy to remember once you split it into two parts:
- Allow rules across policies use OR logic: If multiple policies target the same Pod, their allow rules are combined with an OR operator. For example:
- Policy 1 allows ingress from the
prodnamespace - Policy 2 allows ingress from the
192.168.0.0/24IP range - A Pod targeted by both will accept traffic from either the
prodnamespace or the IP range.
- Policy 1 allows ingress from the
- Conditions within a single rule use AND logic: If a rule has multiple conditions (like a namespace selector plus a pod selector), all conditions must be met. For example, this rule only allows traffic from Pods that are in the
prodnamespace and have theapp: backendlabel:ingress: - from: - namespaceSelector: matchLabels: env: prod podSelector: matchLabels: app: backend - No explicit deny rules exist: Kubernetes Network Policies don’t let you write "deny this traffic" rules. The only way to block traffic is to not include it in any allow rule. Once a Pod is targeted by any policy, all unallowed traffic is automatically blocked.
内容的提问来源于stack exchange,提问作者user1578872

