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

# Writing Egress Policies Hands On

> Guide to writing and troubleshooting Kubernetes NetworkPolicy egress rules, including case sensitive field names, namespace and pod selectors, DNS allowances, and practical examples

So where is the mistake hiding?

Below is the NetworkPolicy manifest Bob first wrote. It looks correct at a glance but contains a subtle, case-sensitive typo:

```yaml theme={null}
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: deny-egress-to-ns
spec:
  podSelector: {}
  policyTypes:
    - Egress
  Egress:
    - to:
      - namespaceSelector:
          matchLabels:
            kubernetes.io/metadata.name: gamma
```

This policy intends to allow egress from selected pods to the `gamma` namespace by matching the built-in namespace label `kubernetes.io/metadata.name: gamma`. When Bob applies it the API server rejects the manifest because YAML object keys are case-sensitive:

```bash theme={null}
$ kubectl apply -f egress-manifest1.yaml
Error from server (BadRequest): error when creating "egress-manifest1.yaml": NetworkPolicy in version "v1" cannot be handled as a NetworkPolicy: strict decoding error: unknown field "spec.Egress"
```

Field names in Kubernetes manifests are case-sensitive. The correct list of egress rules is `egress` (lowercase), while `policyTypes` uses the value `Egress` (capital E). Use `egress:` — not `Egress:` — to define egress rules.

Fixing that one-letter typo produces a valid NetworkPolicy:

```yaml theme={null}
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: deny-egress-to-ns
spec:
  podSelector: {}
  policyTypes:
    - Egress
  egress:
    - to:
      - namespaceSelector:
          matchLabels:
            kubernetes.io/metadata.name: gamma
```

When applied, the corrected policy is created in the `default` namespace and allows egress only to pods in the `gamma` namespace.

## Narrowing the rule to only access-admin pods in Gamma

The previous example permits egress to every pod in `gamma`. To limit access to only pods labeled `app=access-admin` inside `gamma`, include a `podSelector` in the same `to` item. Both selectors are part of the same map and must match simultaneously:

```yaml theme={null}
spec:
  egress:
    - to:
      - namespaceSelector:
          matchLabels:
            kubernetes.io/metadata.name: gamma
        podSelector:
          matchLabels:
            app: access-admin
```

This pattern — combining `namespaceSelector` and `podSelector` inside one `to` map — means the destination must satisfy both conditions. Only pods matching `app=access-admin` in the `gamma` namespace will be reachable.

However, be aware: once a NetworkPolicy selects a pod and includes `policyTypes: ["Egress"]`, any outbound traffic not explicitly allowed by rules is denied. That commonly affects DNS.

![A stylized diagram showing Kubernetes namespaces and pods (cute blue pod icons) with network connections — red marks block some cross-namespace traffic while a green check shows one allowed path to an "access: admin" pod. Labels like "default", "gamma", and "kube-system" and metadata selectors are shown.](https://mintcdn.com/kodekloud-c4ac6d9a/UCHQITKCSrYPqxtk/images/Learn-By-Doing-Kubernetes-Network-Policies/Egress/Writing-Egress-Policies-Hands-On/kubernetes-namespaces-pods-network-policy.jpg?fit=max\&auto=format\&n=UCHQITKCSrYPqxtk\&q=85\&s=eaad08bd3d7a754a3f9fcba3949b70e7)

## Restoring DNS while keeping restrictions

Because the restrictive policy blocks most egress (including DNS), pods in `default` may fail name lookups. To restore DNS while keeping other restrictions, create a second policy that allows egress to port 53 over TCP and UDP to any destination. A `ports` list without a `to` list means "any destination, only these ports":

```yaml theme={null}
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: egress-on-p53
spec:
  podSelector: {}
  policyTypes:
    - Egress
  egress:
    - ports:
      - protocol: TCP
        port: 53
      - protocol: UDP
        port: 53
```

Describe output shows the intent clearly:

```bash theme={null}
$ kubectl describe netpol egress-on-p53
Allowing egress traffic:
    To Port: 53/TCP
    To Port: 53/UDP
    To: <any> (traffic not restricted by destination)
```

Important: when a NetworkPolicy affects egress for a pod, DNS and other outbound traffic will be blocked unless you explicitly allow it (for example, by permitting 53/TCP and 53/UDP).

If all policies are removed, egress reverts to the cluster default (all egress allowed):

```bash theme={null}
$ kubectl delete netpol --all
networkpolicy.networking.k8s.io "deny-egress-to-ns" deleted
networkpolicy.networking.k8s.io "egress-on-p53" deleted
```

## Patterns and real-world examples

Below are common egress patterns and concise examples you can reuse.

| Pattern | Description | Example snippet |
| - | - | - |
| Allow egress to a namespace | Permit egress to any pod in a named namespace | See `egress` with `namespaceSelector` above |
| Allow egress to pods with label in namespace | Restrict by both namespace and pod label (both must match) | `namespaceSelector` + `podSelector` within same `to` item |
| Allow DNS to any destination | Allow DNS for selected pods when general egress is blocked | `egress: - ports: - port: 53 protocol: TCP - port: 53 protocol: UDP` |
| Deny all egress from selected pods | Select pods and set `egress: []` to block all outbound traffic | See `genin-no-egress` example below |
| Multiple allowed destinations | Multiple `to` items under `egress` are ORed (match any) | Use separate `to` elements for each allowed peer |

## Policies for Konoha Corp. — pointing at ramen pods

Konoha Corp. needs pods in the `jonin` namespace to talk to ramen pods in `genin`. The ramen pods carry the label `app: ramen`. The policy below selects all pods in `jonin` and allows egress to ramen pods in the `genin` namespace:

```yaml theme={null}
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: jonin-to-genin
  namespace: jonin
spec:
  podSelector: {}
  policyTypes:
    - Egress
  egress:
    - to:
      - podSelector:
          matchLabels:
            app: ramen
        namespaceSelector:
          matchLabels:
            kubernetes.io/metadata.name: genin
```

Note: `podSelector` and `namespaceSelector` are both inside the same `to` object — both must match for traffic to be allowed.

## Testing by IP (DNS may be blocked)

When DNS is not available, test connectivity with pod IP addresses.

Successful request to a ramen pod:

```bash theme={null}
$ kubectl exec -n jonin chakra -- curl -s -m 3 10.244.0.5
<h1>Welcome to nginx!</h1>
```

A request to a non-allowed pod times out:

```bash theme={null}
$ kubectl exec -n jonin chakra -- curl -s --connect-timeout 3 10.244.0.7
command terminated with exit code 28
```

## Blocking all egress from a namespace

To explicitly forbid any outbound traffic from every pod in the `genin` namespace, create a NetworkPolicy with an empty `egress` array. This isolates selected pods for egress:

```yaml theme={null}
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: genin-no-egress
  namespace: genin
spec:
  podSelector: {}
  policyTypes:
    - Egress
  egress: []
```

Describe output:

```bash theme={null}
$ kubectl describe -n genin netpol genin-no-egress
Allowing egress traffic:
<none> (Selected pods are isolated for egress connectivity)
```

## Allowing specific peers for Hokage

In the `default` namespace, Bob wants the `hokage` pod to be able to reach either ramen pods in `genin` or chakra pods in `jonin`. Each `to` item is an independent allowed destination (logical OR):

```yaml theme={null}
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: hokage-allow
  namespace: default
spec:
  podSelector:
    matchLabels:
      app: hokage
  policyTypes:
    - Egress
  egress:
    - to:
      - podSelector:
          matchLabels:
            app: ramen
        namespaceSelector:
          matchLabels:
            kubernetes.io/metadata.name: genin
    - to:
      - podSelector:
          matchLabels:
            app: chakra
        namespaceSelector:
          matchLabels:
            kubernetes.io/metadata.name: jonin
```

## Allowing DNS-only egress from Genin

To make the `genin` namespace silent except for DNS, replace the empty `egress` array from `genin-no-egress` with a ports-only rule that permits only port 53 for TCP and UDP:

```yaml theme={null}
spec:
  podSelector: {}
  policyTypes:
    - Egress
  egress:
    - ports:
      - port: 53
        protocol: TCP
      - port: 53
        protocol: UDP
```

This lets `genin` pods perform name lookups while disallowing all other outbound connections.

## Pod-level control down to a single port

NetworkPolicy lets you control egress precisely across namespaces and between pods — down to a single protocol/port. Keep these patterns in mind:

* Combine `namespaceSelector` and `podSelector` inside one `to` item to require both conditions.
* Use multiple `to` items under the same `egress` entry to allow multiple independent destinations (OR logic).
* Use `egress: []` to block all outbound traffic for selected pods.
* Use `egress` entries with only `ports` (no `to`) to permit specified ports to any destination (useful for DNS).

## So what happens when a whole cluster needs all of that at once?

When you need cluster-wide policy coverage, follow these practical steps:

1. Audit existing NetworkPolicies and default behavior — understand which namespaces/pods already have restrictions.
2. Design minimal allow-lists: start by allowing DNS and essential control-plane traffic, then add application-specific rules.
3. Apply policies progressively, testing connectivity (by IP when DNS may be restricted).
4. Use namespace-scoped policies to contain rules and simplify management.
5. Document and version your policies with GitOps for reproducibility.

## Links and references

* [Kubernetes NetworkPolicy documentation](https://kubernetes.io/docs/concepts/services-networking/network-policies/)
* [NetworkPolicy API reference](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.27/#networkpolicy-v1-networking-k8s-io)
* [Kubernetes Networking Concepts](https://kubernetes.io/docs/concepts/cluster-administration/networking/)

## Further reading and examples

* For patterns and real-world examples, search for "NetworkPolicy egress patterns", "allow DNS NetworkPolicy", and "namespaceSelector podSelector examples" in the Kubernetes docs and trusted community blogs.

> [card] [Watch Video](https://learn.kodekloud.com/user/courses/learn-by-doing-kubernetes-network-policies/module/66346eea-5872-4503-9fbc-8ba7e0b7ac5b/lesson/98cec767-e37a-402b-a004-96d425c61066)

> [card] [Practice Lab](https://learn.kodekloud.com/user/courses/learn-by-doing-kubernetes-network-policies/module/66346eea-5872-4503-9fbc-8ba7e0b7ac5b/lesson/f49e4228-9123-4089-b885-53fffeeae658)


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