> ## 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.

# Isolating Namespaces The Problem

> Kubernetes NetworkPolicy techniques to isolate namespaces and permit cross-namespace traffic using deny-all ingress, namespaceSelector, and combined namespaceSelector and podSelector rules.

Bob's Kubernetes cluster is no longer a single namespace. Production, QA, and logging each live in their own namespace, and traffic can flow between them. Up to now, every NetworkPolicy Bob has written scoped to pods inside the same namespace. Can a NetworkPolicy control traffic coming from a pod in a different namespace? Bob explores that through three progressively stricter scenarios.

Quick overview (what you'll learn)

* How `deny-all` ingress isolates a namespace.
* How to allow an entire namespace using `namespaceSelector`.
* How to allow only specific pods from another namespace by combining `namespaceSelector` and `podSelector`.

| Scenario | Goal | Key NetworkPolicy selector |
| - | -: | - |
| 1 | Block all ingress to `production`, then allow only specific pod-to-pod paths. | `podSelector` with explicit allow rules |
| 2 | Allow every pod from a logging namespace `alpha-logger` into `alpha-prod`. | `namespaceSelector` |
| 3 | Allow only pods labeled `role=logger1` from `beta-logger` into `beta-prod`. | `namespaceSelector` + `podSelector` |

Scenario 1 — Restrict production and open specific paths

* The three-tier app lives in namespace `production` with frontend (2 pods), middleware, and MySQL pods and services.
* Two tester pods exist in other namespaces: `default` (default tester) and `qa` (qa tester).
* Initially there are no policies in `production`, so both testers can reach the production pods.

Bob's goal: keep outside testers and unwanted pod-to-pod access out of `production`, while preserving only the necessary app flows:

1. Create a `deny-all-ingress` policy in `production`.
2. Allow frontend -> middleware using labels already on the pods.
3. Allow middleware -> MySQL using labels already on the pods.

To validate connectivity, Bob uses netcat (`nc`) from tester pods. To reach a service in another namespace, testers use the service FQDN: `service-name.namespace.svc` (for example: `middleware-service.production.svc`).

![A stylized Kubernetes network diagram titled "Still No Path to mysql" showing namespaces and friendly service icons (default/qa testers, frontend, middleware, mysql). Red dashed lines and a "deny-all-ingress" policy mark blocked connections to MySQL while a green arrow shows an allowed path from middleware.](https://mintcdn.com/kodekloud-c4ac6d9a/UCHQITKCSrYPqxtk/images/Learn-By-Doing-Kubernetes-Network-Policies/Namespace-Isolation/Isolating-Namespaces-The-Problem/kubernetes-still-no-path-to-mysql.jpg?fit=max\&auto=format\&n=UCHQITKCSrYPqxtk\&q=85\&s=9661baaf1ceeb84a4704d1fb8a529635)

Example NetworkPolicy: deny all ingress in the `production` namespace

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

Example NetworkPolicy: allow frontend pods to reach middleware (within `production`)

```yaml theme={null}
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-frontend-to-middleware
  namespace: production
spec:
  podSelector:
    matchLabels:
      app: middleware
  policyTypes:
    - Ingress
  ingress:
    - from:
        - podSelector:
            matchLabels:
              app: frontend
```

Example NetworkPolicy: allow middleware to talk to MySQL (within `production`)

```yaml theme={null}
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-middleware-to-mysql
  namespace: production
spec:
  podSelector:
    matchLabels:
      app: mysql
  policyTypes:
    - Ingress
  ingress:
    - from:
        - podSelector:
            matchLabels:
              app: middleware
```

After applying these three policies:

* Testers in `default` and `qa` should be blocked from production services unless explicitly permitted.
* The frontend can reach middleware.
* Middleware can reach MySQL.
* The frontend should remain blocked from talking directly to MySQL.

Scenario 2 — Allow an entire namespace in

* Namespace `alpha-prod` contains two app pods and an existing `deny-all` policy blocking incoming traffic.
* Namespace `alpha-logger` runs centralized logging and must access `alpha-prod` to collect logs across the cluster.
* Both namespaces share a namespace-level label: `function=logging` (that label is applied to the Namespace object, not the pods).

Requirement: create a policy called `allow-alpha-logger` inside `alpha-prod` that permits all pods from namespaces labeled `function=logging` to access the `alpha-prod` pods, without changing any existing pod labels.

Important selector behavior: a `podSelector` inside a `from` clause only matches pods in the policy's own namespace. To select pods from another namespace, use `namespaceSelector` in the peer.

Example NetworkPolicy that allows all pods from namespaces labeled `function=logging`:

```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
```

A `namespaceSelector` in a NetworkPolicyPeer selects namespaces by their labels. To restrict further to specific pods within those namespaces, combine `namespaceSelector` with a `podSelector` in the same peer — the result matches pods in the selected namespaces that also match the pod selector.

Scenario 3 — Allow only a specific kind of pod from a logging namespace

* Namespace `beta-prod` has the same deny-all policy.
* Namespace `beta-logger` is labeled `function=logging`, but only pods with `role=logger1` inside that namespace should be allowed into `beta-prod`.
* Bob needs a policy `allow-beta-logger-1` that permits ingress into `beta-prod` only from pods labeled `role=logger1` inside namespaces labeled `function=logging`.

To enforce both constraints (which namespace and which pods), you provide both a `namespaceSelector` and a `podSelector` in the same `from` entry.

![A diagram titled "Only role=logger-1 Gets In" showing user "Bob", a beta-logger pod labeled role=logger-1, and two beta-prod pods with a dashed arrow from the logger to beta-pod-1. Network policy badges "deny-all" and "allow-beta-logger-1" indicate only the logger-1 role is allowed access.](https://mintcdn.com/kodekloud-c4ac6d9a/UCHQITKCSrYPqxtk/images/Learn-By-Doing-Kubernetes-Network-Policies/Namespace-Isolation/Isolating-Namespaces-The-Problem/only-role-logger-1-gets-in.jpg?fit=max\&auto=format\&n=UCHQITKCSrYPqxtk\&q=85\&s=9bba04a9763284d73c1e47d3326ea37e)

Example NetworkPolicy that allows only `role=logger1` pods coming from namespaces labeled `function=logging`:

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

How the scenarios build on one another

1. Start by keeping other namespaces out with a `deny-all` ingress policy. This establishes a secure default-deny posture for the namespace.
2. Use `namespaceSelector` to allow an entire external namespace (by namespace label) to access pods.
3. Use `namespaceSelector` together with `podSelector` to allow only specific pods from a labeled namespace.

![A dark-themed infographic titled "How the Scenarios Build" showing three ascending columns numbered 1, 2, and 3 labeled with policies: "deny-all-ingress", "allow-alpha-logger", and "allow-beta-logger-1". A circular avatar labeled "Bob" is on the left and a KodeKloud logo appears in the bottom corner.](https://mintcdn.com/kodekloud-c4ac6d9a/UCHQITKCSrYPqxtk/images/Learn-By-Doing-Kubernetes-Network-Policies/Namespace-Isolation/Isolating-Namespaces-The-Problem/scenarios-build-policies-bob-kodekloud.jpg?fit=max\&auto=format\&n=UCHQITKCSrYPqxtk\&q=85\&s=39fdbf28ca11c22e9d9a5ff6a2934723)

Labeling namespaces for `namespaceSelector` matching

```bash theme={null}
kubectl label namespace alpha-logger function=logging
kubectl label namespace beta-logger function=logging
```

Testing tips and verification

* From tester pods in other namespaces, use netcat to probe service FQDNs like `service.namespace.svc` to confirm connectivity:
  * Example: `nc -vz middleware.production.svc 3306` (adjust ports to the service being tested).
* When a `deny-all` NetworkPolicy exists in a namespace, you must create explicit allow rules (NetworkPolicies that permit ingress) for any traffic you want to allow.
* Use `kubectl get networkpolicy -n <namespace>` and `kubectl describe networkpolicy <name> -n <namespace>` to inspect applied policies and their peers.
* For debugging, check Pod and Namespace labels (`kubectl get ns --show-labels`, `kubectl get pods --show-labels -n <namespace>`) to ensure selectors will match as intended.

By following these patterns you can enforce cross-namespace restrictions and fine-grained access using `namespaceSelector` and `podSelector` in Kubernetes NetworkPolicies.

> [card] [Watch Video](https://learn.kodekloud.com/user/courses/learn-by-doing-kubernetes-network-policies/module/f46d443c-ca94-48e4-8468-f917cd94e792/lesson/83662a5d-fae0-46e9-a4e0-1e5d3ac4a7a1)


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