Network Security with NetworkPolicies
By default, Kubernetes is a very friendly environment. Every pod inside a cluster can talk to every other pod, even if they are in completely different namespaces. While this makes early development easy, it is a nightmare for network security. If a hacker breaches your public-facing web server, they can easily pivot and connect directly to your internal database.
To fix this, we use NetworkPolicies. A NetworkPolicy acts like a virtual firewall for your pods. It allows you to lock down your network by applying a "deny-all" security posture, meaning nothing can communicate unless you explicitly write a rule to allow it.
- How Kubernetes handles network traffic by default.
- How to implement a "deny-all" security posture for your namespaces.
- How to write fine-grained Ingress (incoming) and Egress (outgoing) rules.
- How to securely connect pods using labels and namespace selectors.
1. Understanding NetworkPolicies & Traffic Flow
Before we write code, we need to understand the vocabulary of Kubernetes networking. A NetworkPolicy controls traffic based on endpoints (like pods or namespaces) and ports. It divides traffic into two distinct directions: Ingress and Egress.
| Traffic Type | Definition | Default Behavior |
|---|---|---|
| Ingress | Traffic coming into your pod from somewhere else. | Allow All (Pods accept traffic from anywhere) |
| Egress | Traffic leaving from your pod to somewhere else. | Allow All (Pods can talk to the internet and internal services) |
| Deny-All Default | A foundational security rule that blocks everything. | Must be explicitly applied using a NetworkPolicy. |
When you apply a NetworkPolicy to a pod, that pod becomes "isolated". Once isolated, it will instantly reject all traffic that is not explicitly allowed by a rule.
2. Practical Implementation & Code
Let's build a secure architecture. We will start by blocking everything in our namespace. Then, we will carefully poke a hole in our firewall so our Frontend pod can talk to our Backend pod.
Implementing the "Deny-All" Policy
This is the most critical file in your cluster. By deploying this to your namespace, you instantly stop all lateral movement by an attacker. No pod can send or receive data until you say so.
Example 1: The Default Deny-All NetworkPolicy (YAML)
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny-all
namespace: secure-namespace
spec:
podSelector: {} # The empty bracket matches ALL pods in this namespace
policyTypes:
- Ingress
- Egress
Expected outcome
networkpolicy.networking.k8s.io/default-deny-all created All pods in 'secure-namespace' are now completely isolated.
Writing Fine-Grained Allow Rules
Now that everything is blocked, let's allow our `frontend` app to send traffic to our `backend` app on port 8080. We do this by targeting the pod's labels.
Example 2: Allowing Ingress from Frontend to Backend
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-frontend-to-backend
namespace: secure-namespace
spec:
# 1. Which pod does this rule protect? The backend.
podSelector:
matchLabels:
app: backend
policyTypes:
- Ingress
# 2. What traffic is allowed INTO the backend?
ingress:
- from:
- podSelector:
matchLabels:
app: frontend
ports:
- protocol: TCP
port: 8080
3. Architecture / Workflow Visualized
When you apply these rules, your Kubernetes Container Network Interface (CNI) like Calico or Cilium enforces them at the network layer using eBPF or iptables. Below is a visual representation of how our rules route the traffic.
NetworkPolicy Enforcement in Action
The NetworkPolicy acts as a strict checkpoint. The frontend is allowed through because its labels match the rule. The rogue pod is silently dropped.
4. Step-by-Step Execution Breakdown
Here is exactly how the Kubernetes CNI evaluates network traffic when your pods communicate.
5. Hands-On Practice
Theory is good, but building the YAML files builds muscle memory. Try these exercises in a local Minikube or kind cluster.
Create a namespace called `secure-zone`. Write a NetworkPolicy that drops all incoming and outgoing traffic for every pod in this namespace.
Hint: Use an empty `podSelector: {}` to match all pods.
You applied a deny-all egress policy, and now your pods are crashing because they can't resolve database hostnames. Write a rule that allows egress traffic to the `kube-system` namespace on UDP port 53.
Expected result: Your pod should be able to run `nslookup kubernetes.default.svc.cluster.local` successfully.
Write an Ingress policy for a database pod in the `db-tier` namespace. It should only accept traffic on port 5432 from pods labelled `app: api` that live inside a namespace labelled `environment: production`.
Hint: You must combine `podSelector` and `namespaceSelector` inside the same `- from:` block.
6. Interview Questions
If you are applying for a Senior DevOps or Platform Engineering role, expect to be grilled on network isolation. Here is what they will ask.
Answer: By default, Kubernetes pods are "non-isolated". This means they accept all incoming traffic from any source, and can send outgoing traffic to any destination. A pod only becomes "isolated" the moment a NetworkPolicy selects it.
Answer: You use the `ipBlock` field inside your ingress or egress rules. You can specify a CIDR block (like `192.168.1.0/24`) to allow, and use the `except` array within that block to explicitly exclude specific IP addresses from that range.
Answer: Nothing happens. The API server will accept and store the NetworkPolicy object, but Flannel does not support NetworkPolicy enforcement. The rules will simply be ignored. You must use a CNI that supports enforcement, such as Calico, Cilium, or Weave Net.
Conclusion
Relying on the cluster edge (like a cloud firewall or Ingress Controller) is no longer enough to secure modern microservices. If an attacker breaches the perimeter, a flat internal network gives them the keys to the kingdom. By implementing a default "deny-all" NetworkPolicy and carefully managing your Ingress and Egress rules via pod labels, you create a zero-trust architecture right down to the container level. Start small, verify your traffic logs, and incrementally lock down your namespaces.
Official Documentation
Upgradix by Shrash Studio – Learn Technology. Build Your Future.