LATEST 🚀 Welcome to Upgradix by Shrash Studio – Your destination for free technology learning and career growth.
🕘 Updated:
Kubernetes

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.

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.

What you will learn
  • 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.
Important: After applying a deny-all egress policy, your pods will not be able to reach the Kubernetes DNS server (CoreDNS). They won't be able to resolve database URLs until you explicitly allow DNS egress on UDP port 53.

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

Frontend Pod Rogue Pod Backend Pod Port 8080 NetworkPolicy Barrier Allowed (Port 8080) Blocked (Denied)

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.

Step 1: Traffic is initiated. The frontend pod attempts to open a TCP connection to the backend pod's IP address on port 8080.
Step 2: CNI intercepts the request. The networking plugin (like Calico) pauses the packet and checks the backend's `NetworkPolicy` rules.
Step 3: Evaluating the Deny-All rule. The CNI sees the default deny-all policy. The baseline decision is to DROP the packet.
Step 4: Checking for explicit allowances. The CNI reads the `allow-frontend-to-backend` policy. It verifies that the source pod has the label `app: frontend` and the destination port is exactly 8080.
Step 5: Connection established. Because an explicit allow rule was found, it overrides the default deny. The packet is passed to the backend application container.
Watch out: NetworkPolicies are additive. If you have two policies targeting the same pod, and one denies traffic while the other allows it, the traffic is allowed. There is no concept of a "deny" rule that overrides an "allow" rule in standard Kubernetes.

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.

Beginner Exercise 1: Isolate a Namespace

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.

Intermediate Exercise 2: Allow DNS Lookups

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.

Advanced Exercise 3: Cross-Namespace Communication

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.

Q1. If a pod has no NetworkPolicy applied to it, what traffic is allowed?

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.

Q2. How do you block traffic from a specific IP address using NetworkPolicies?

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.

Q3. If I create a NetworkPolicy, but my cluster uses standard Flannel as the CNI, what happens?

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.

Comments & Ratings (0)

Log in or create a student account to comment and rate this article.

Be the first to comment on this article.