Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 78 ยท Services and Networking

Network Policies

Learn how Kubernetes NetworkPolicy works: default allow, deny-all, ingress and egress rules, selector semantics, the CNI requirement and common patterns.

Out of the box, every Pod in a Kubernetes cluster can open a connection to every other Pod, in any namespace. That is convenient while learning and dangerous in production: one compromised web Pod can talk straight to your database. A NetworkPolicy is how you turn that flat network into something closer to a set of firewall rules, written in terms of labels instead of IP addresses.

In this lesson you will learn the default behavior, how policies select Pods, how ingress and egress rules are combined, the one rule that confuses almost everyone (AND versus OR in selectors), and a few patterns you will use again and again. A Python evaluator at the end lets you test rule sets yourself.

NetworkPolicy objects are only instructions. The enforcement is done by your network plugin (see Pod Networking and CNI). If the plugin does not support policies, for example plain Flannel, the API server accepts your policy and nothing happens. Always test that a blocked connection is really blocked.

Default allow, then isolation

A Pod with no policy selecting it is non-isolated: it accepts traffic from anywhere and may send traffic anywhere. The moment at least one NetworkPolicy selects a Pod for a direction, that Pod becomes isolated for that direction, and only traffic permitted by some policy is allowed.

How isolation works

No policy Everything is allowed, both directions.
Selected by a policy That direction is now deny by default.
Rules add allowances Policies only ever allow, never deny.

Several policies on one Pod are combined as a union.

1 / 2

Two consequences follow. There is no "deny" rule: you restrict by selecting Pods and then allowing only what you need. And policies never conflict, because they only add allowances.

Your first policies: deny everything

The standard starting point for a locked-down namespace is a pair of policies with an empty podSelector, which means "every Pod in this namespace":

YAML
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny-ingress
  namespace: shop
spec:
  podSelector: {}
  policyTypes:
    - Ingress
YAML
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny-egress
  namespace: shop
spec:
  podSelector: {}
  policyTypes:
    - Egress

There are no ingress or egress lists, so no traffic is allowed in the listed directions. After applying both, nothing in the shop namespace can receive connections or make them, including DNS lookups. That last part is the first thing that bites people, so you will usually pair deny-egress with a DNS allowance (shown below).

Replies to allowed connections are always allowed; you do not write a rule for return packets. Also, traffic from a Pod to its own node (for example kubelet health probes) is normally permitted by the plugin so that probes keep working.

Allowing specific traffic

Now let the frontend reach the API, and only the frontend:

YAML
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: api-from-frontend
  namespace: shop
spec:
  podSelector:
    matchLabels:
      app: api
  policyTypes:
    - Ingress
  ingress:
    - from:
        - podSelector:
            matchLabels:
              app: frontend
      ports:
        - protocol: TCP
          port: 8080

Read it from the top: this policy applies to Pods labeled app=api (the podSelector at the top of spec says whom the policy protects). The ingress rule allows connections from Pods labeled app=frontend in the same namespace, on TCP port 8080 only. Everything else heading for those API Pods is dropped.

For egress, the structure mirrors ingress but uses to. A typical egress allowance for the API lets it reach its database and DNS:

YAML
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: api-egress
  namespace: shop
spec:
  podSelector:
    matchLabels:
      app: api
  policyTypes:
    - Egress
  egress:
    - to:
        - podSelector:
            matchLabels:
              app: db
      ports:
        - protocol: TCP
          port: 5432
    - to:
        - namespaceSelector:
            matchLabels:
              kubernetes.io/metadata.name: kube-system
          podSelector:
            matchLabels:
              k8s-app: kube-dns
      ports:
        - protocol: UDP
          port: 53
        - protocol: TCP
          port: 53

The kubernetes.io/metadata.name label is added to every namespace automatically, which makes it a reliable way to refer to a namespace by name. Your cluster's DNS Pods may use different labels, so check them with kubectl get pods -n kube-system --show-labels.

The AND versus OR trap

Each item in a from or to list is a peer. A peer can use podSelector, namespaceSelector or ipBlock. What matters is whether selectors share one list item:

YAML
# AND: Pods labeled role=client that are ALSO in namespaces labeled team=web
- from:
    - namespaceSelector:
        matchLabels: { team: web }
      podSelector:
        matchLabels: { role: client }

# OR: any Pod in a team=web namespace, OR any role=client Pod in this namespace
- from:
    - namespaceSelector:
        matchLabels: { team: web }
    - podSelector:
        matchLabels: { role: client }

The only difference is a single dash. Within one peer, selectors are ANDed. Separate peers are ORed. Getting this wrong typically opens far more access than intended. The same is true of ports: entries in ports are alternatives.

Use ipBlock for addresses outside the cluster, such as a managed database or an office network. It takes a cidr and optional except list. Do not use it for Pod IPs, which change.

Patterns worth knowing

  • Default deny plus explicit allows. Begin every namespace with the two deny policies, then add one policy per allowed flow, named after the flow (api-from-frontend).
  • Allow from the ingress controller. Let the namespace of your ingress controller (selected by its namespace label) reach the web Pods.
  • Allow monitoring. Permit the Prometheus namespace to scrape the metrics port of every Pod.
  • Isolate namespaces. A policy with from: - podSelector: {} allows only Pods of the same namespace.
  • Restrict egress to the internet. Allow 0.0.0.0/0 with an except for private ranges, so Pods can reach public APIs but not your internal network.

Some plugins add their own, richer policy objects (Calico's GlobalNetworkPolicy, Cilium's CiliumNetworkPolicy with HTTP and DNS-name rules). They go beyond the standard API, so use them deliberately.

A policy evaluator you can run

This stand-in implements the core semantics: isolation per direction, union of allowances, AND within a peer, OR across peers, and port checks. It is a model of the rules, not a real packet filter.

Python Would this connection be allowed?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The frontend -> db call is denied because the deny-ingress policy isolates every Pod and no other policy opens the database. Scraping works because the scrape policy selects all Pods and allows the Prometheus Pod from the ops namespace.

Python Spot the one-dash mistake (AND vs OR)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The OR version admits web-batch, which was never meant to connect. Always review the dashes.

Testing and debugging policies

Check that policies exist with kubectl get networkpolicy -n shop and read one with kubectl describe networkpolicy api-from-frontend -n shop. To prove a rule works, run a throwaway Pod and try the connection:

Terminal
kubectl run probe --rm -it --image=busybox:1.37 --restart=Never -n shop \
  --labels="app=frontend" -- wget -qO- -T 3 http://api:8080/health

Labeling the probe Pod as app=frontend lets it pass the allow rule; run it again without the label and the request should time out. A timeout (not "connection refused") is the typical symptom of a policy drop.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A namespace has no NetworkPolicy objects. What can its Pods do?

    Kubernetes networking is open by default. Pods become isolated for a direction only when a policy selects them for that direction.
  2. 2. Which policy blocks all incoming traffic to every Pod in the namespace?

    An empty podSelector selects all Pods. Listing Ingress without any ingress rules means nothing is allowed in.
  3. 3. In a from list, a namespaceSelector and a podSelector are written inside the same list item. How are they combined?

    Selectors inside one peer are ANDed. Putting them in two separate list items would make them alternatives (OR).
  4. 4. You apply a correct NetworkPolicy on a cluster that uses a CNI plugin without policy support. What happens?

    The API only stores the object. Enforcement is the network plugin's job, so an unsupported plugin silently ignores it.

Summary

  • Pods are open to all traffic until a NetworkPolicy selects them for a direction; then only allowed traffic passes.
  • Policies only allow, they are combined as a union, and replies to allowed connections are automatic.
  • Start with deny-all for ingress and egress, then add one named policy per flow, and do not forget DNS egress.
  • Selectors in one peer are ANDed, separate peers are ORed; ipBlock is for addresses outside the cluster.
  • Enforcement needs a CNI plugin that supports NetworkPolicy; always test with a throwaway Pod.

Next: how Pods get their IP addresses and how the network plugin connects them in Pod Networking and CNI.