> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Namespace Selectors Hands On

> Hands-on Kubernetes NetworkPolicy guide demonstrating namespace isolation and precise cross-namespace exceptions using deny-all, namespaceSelector, and combined namespace plus pod selectors

This guide walks through practical NetworkPolicy patterns that enforce namespace isolation while allowing precise cross-namespace exceptions. We keep Bob's examples and sequence: start with a closed production environment, then add namespace-scoped allow rules (alpha-prod), and finish with a combined namespace+pod selector (beta-prod).

## Production: deny-all-ingress, then allow specific app-to-app traffic

Begin by denying all ingress to pods in the `production` namespace. The policy below uses an empty `podSelector` (`{}`) to select every pod in `production`, sets `policyTypes` to only `Ingress`, and provides no `ingress` rules — which means "deny all ingress" to the selected pods.

```yaml theme={null}
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: deny-all-ingress
  namespace: production
spec:
  podSelector: {}
  policyTypes:
  - Ingress
```

Then apply two allow policies (both in the `production` namespace):

* `allow-frontend-to-middleware` — protects the middleware pods and permits ingress from pods labeled `app=frontend` (in `production`).
* `allow-middleware-to-mysql` — protects MySQL pods and permits ingress from pods labeled `app=middleware` (in `production`).

Important: because `podSelector` and the `from` entries are provided without a `namespaceSelector`, they only match pods in the same namespace as the policy. A QA or dev tester in another namespace with `app=frontend` will not be matched by these rules.

Apply the policies:

```bash theme={null}
$ kubectl apply -f production/
networkpolicy.networking.k8s.io/deny-all-ingress created
networkpolicy.networking.k8s.io/allow-frontend-to-middleware created
networkpolicy.networking.k8s.io/allow-middleware-to-mysql created
```

Verify cross-namespace connectivity is blocked (examples show attempts from `qa` and `dev` namespaces to the middleware service in `production` — both are blocked):

```bash theme={null}
$ kubectl -n qa exec qa-tester -- nc -z -w1 middleware-svc.production.svc 80
command terminated with exit code 1

$ kubectl -n dev exec dev-tester -- nc -z -w1 middleware-svc.production.svc 80
command terminated with exit code 1
```

Internal flows are allowed as intended: frontend -> middleware and middleware -> mysql succeed, while frontend -> mysql is still blocked. All five verification checks pass: production is closed to other namespaces but allows the intended internal app communication.

![A stylized network diagram titled "Closed to Other Namespaces" showing Kubernetes namespaces (default, qa, production) with blue service icons labeled default-tester, qa-tester and production apps (app=frontend, app=middleware, app=mysql). Red blocked lines and green arrows illustrate network policies (including a "deny-all-ingress" rule) that block cross-namespace traffic while allowing specific internal connections.](https://mintcdn.com/kodekloud-c4ac6d9a/UCHQITKCSrYPqxtk/images/Learn-By-Doing-Kubernetes-Network-Policies/Namespace-Isolation/Namespace-Selectors-Hands-On/k8s-closed-namespaces-network-policies.jpg?fit=max\&auto=format\&n=UCHQITKCSrYPqxtk\&q=85\&s=f22aba904d9b24ce42c842784730c607)

Policy summary

| Policy name | Namespace | Purpose | Selectors / Notes |
| - | - | - | - |
| `deny-all-ingress` | `production` | Block all ingress to production pods | `podSelector: {}` (selects all pods in the namespace) |
| `allow-frontend-to-middleware` | `production` | Allow frontend -> middleware | `from` matches pods with `app=frontend` (same namespace) |
| `allow-middleware-to-mysql` | `production` | Allow middleware -> MySQL | `from` matches pods with `app=middleware` (same namespace) |

## alpha-prod: allow ingress from a logging namespace (namespaceSelector)

If the source pods you want to allow live in another namespace, use `namespaceSelector`. A `podSelector` inside a policy selects pods only from the policy's namespace; to select pods from other namespaces, add a `namespaceSelector` that matches namespace labels.

Example: allow all pods in `alpha-prod` to accept ingress from any namespace labeled `function=logging`. This policy is placed in `alpha-prod` and selects all pods there via `podSelector: {}`:

```yaml theme={null}
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-alpha-logger
  namespace: alpha-prod
spec:
  podSelector: {}
  policyTypes:
  - Ingress
  ingress:
  - from:
    - namespaceSelector:
        matchLabels:
          function: logging
```

Read the `from` entry aloud: "from a namespace where `function` equals `logging`." Because NetworkPolicies are additive, an existing deny-all policy in `alpha-prod` remains; this allow simply opens that specific path on top of the deny-all baseline.

NetworkPolicy peers are evaluated relative to the policy's namespace. A `podSelector` without a `namespaceSelector` matches only pods in the same namespace as the policy. To match pods in other namespaces, include a `namespaceSelector`.

See also: [Kubernetes NetworkPolicy concepts](https://kubernetes.io/docs/concepts/services-networking/network-policies/).

## beta-prod: require both namespace label AND pod label on the source (namespaceSelector + podSelector)

When both namespace-level and pod-level constraints must apply to the same source, put `namespaceSelector` and `podSelector` together in the same peer mapping (same list item) under `from`. That groups selectors with a logical AND.

Start with the top-level policy metadata (this policy lives in `beta-prod` and selects all pods in that namespace):

```yaml theme={null}
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-beta-logger
  namespace: beta-prod
spec:
  podSelector: {}
  policyTypes:
  - Ingress
```

To require that the source pod is both in a namespace labeled `function=logging` AND has `role=logger-1`, combine selectors into the same peer mapping (single dash):

```yaml theme={null}
ingress:
- from:
  - namespaceSelector:
      matchLabels:
        function: logging
    podSelector:
      matchLabels:
        role: logger-1
```

Because `namespaceSelector` and `podSelector` are keys of the same mapping (the same list item in the `from` list), both must match for the traffic to be allowed: the source must be a pod labeled `role=logger-1` inside a namespace labeled `function=logging`.

Contrast: if you place `namespaceSelector` and `podSelector` as separate list items (each with its own dash), you create an OR between those peers:

```yaml theme={null}
ingress:
- from:
  - namespaceSelector:
      matchLabels:
        function: logging
  - podSelector:
      matchLabels:
        role: logger-1
```

That configuration allows ingress from either:

* any pod in a namespace labeled `function=logging`, OR
* any pod in the same namespace as the policy labeled `role=logger-1`.

This OR is almost always broader than intended if you meant to require both conditions.

## Final reminder: Ingress vs Egress

All of the policies above control only what may *enter* selected pods (Ingress). Pods are still free to initiate outbound connections (Egress) unless you define explicit Egress rules. If you need to restrict outbound traffic as well, add corresponding Egress policies.

Additional references

* [Kubernetes NetworkPolicy documentation](https://kubernetes.io/docs/concepts/services-networking/network-policies/)
* [Understanding NetworkPolicy selectors and peers](https://kubernetes.io/docs/concepts/services-networking/network-policies/#networkpolicy-peer)

> [card] [Watch Video](https://learn.kodekloud.com/user/courses/learn-by-doing-kubernetes-network-policies/module/f46d443c-ca94-48e4-8468-f917cd94e792/lesson/bf8127b9-8142-4dd0-807c-d6fffcda9c2f)

> [card] [Practice Lab](https://learn.kodekloud.com/user/courses/learn-by-doing-kubernetes-network-policies/module/f46d443c-ca94-48e4-8468-f917cd94e792/lesson/3020fac2-12f4-4306-abd6-d85456973abd)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.