0
0
Kubernetesdevops~15 mins

Network policies for security in Kubernetes - Deep Dive

Choose your learning style9 modes available
Overview - Network policies for security
What is it?
Network policies in Kubernetes are rules that control how groups of pods communicate with each other and with other network endpoints. They act like traffic lights or gates, deciding which connections are allowed or blocked. These policies help secure the cluster by limiting access to only trusted sources. Without them, any pod could talk to any other pod, increasing security risks.
Why it matters
Without network policies, all pods in a Kubernetes cluster can freely communicate, which can lead to accidental or malicious access to sensitive services. Network policies help prevent attacks like data leaks or unauthorized access by restricting traffic. This makes your applications safer and helps meet security standards. Imagine a building with open doors everywhere versus one with controlled access points; network policies create those controlled doors.
Where it fits
Before learning network policies, you should understand Kubernetes pods, services, and basic networking concepts like IP addresses and ports. After mastering network policies, you can explore advanced security topics like service meshes, pod security policies, and Kubernetes RBAC (Role-Based Access Control).
Mental Model
Core Idea
Network policies are like security guards that decide which pods can talk to which others, controlling traffic flow inside a Kubernetes cluster.
Think of it like...
Think of a Kubernetes cluster as an office building with many rooms (pods). Network policies are the security guards who check badges and decide who can enter which rooms and who can’t, ensuring only authorized people meet.
┌───────────────────────────────┐
│ Kubernetes Cluster Network     │
│                               │
│  ┌─────────┐   ┌─────────┐    │
│  │ Pod A   │──▶│ Pod B   │    │
│  └─────────┘   └─────────┘    │
│       ▲            │          │
│       │            ▼          │
│  ┌─────────┐   ┌─────────┐    │
│  │ Pod C   │   │ Pod D   │    │
│  └─────────┘   └─────────┘    │
│                               │
│ Network Policy controls arrows│
└───────────────────────────────┘
Build-Up - 7 Steps
1
FoundationWhat are Kubernetes Network Policies
🤔
Concept: Introduce the basic idea of network policies as rules that control pod communication.
In Kubernetes, pods are the smallest units that run your applications. By default, all pods can talk to each other without restrictions. Network policies let you define rules to allow or block traffic between pods based on labels, namespaces, and ports.
Result
Learners understand that network policies are security rules controlling pod-to-pod communication.
Understanding that Kubernetes does not restrict pod communication by default highlights why network policies are essential for security.
2
FoundationBasic Structure of a Network Policy
🤔
Concept: Explain the main parts of a network policy: pod selector, ingress and egress rules.
A network policy has three main parts: 1. Pod Selector: chooses which pods the policy applies to. 2. Ingress Rules: define what incoming traffic is allowed. 3. Egress Rules: define what outgoing traffic is allowed. Each rule can specify allowed IP blocks, ports, or other pods by labels.
Result
Learners can identify the components of a network policy YAML file.
Knowing the structure helps learners write and understand policies that precisely control traffic.
3
IntermediateHow to Write an Ingress Network Policy
🤔Before reading on: do you think a network policy blocks all traffic by default or allows all traffic by default? Commit to your answer.
Concept: Show how to create a policy that restricts incoming traffic to specific pods and ports.
Example YAML: apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: allow-nginx-ingress spec: podSelector: matchLabels: app: nginx policyTypes: - Ingress ingress: - from: - podSelector: matchLabels: role: frontend ports: - protocol: TCP port: 80 This policy allows only pods with label role=frontend to connect to pods labeled app=nginx on port 80.
Result
Pods labeled app=nginx accept traffic only from frontend pods on TCP port 80; other traffic is blocked.
Understanding that network policies are deny-by-default for selected pods clarifies how to secure services by explicitly allowing trusted sources.
4
IntermediateUsing Egress Rules to Control Outgoing Traffic
🤔Before reading on: do you think egress rules control incoming or outgoing traffic? Commit to your answer.
Concept: Explain how to restrict what pods can connect to outside the cluster or other pods.
Example YAML: apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: deny-all-egress spec: podSelector: matchLabels: app: backend policyTypes: - Egress egress: [] This policy blocks all outgoing traffic from pods labeled app=backend, preventing them from reaching any external or internal endpoints.
Result
Pods labeled app=backend cannot send any network traffic outside themselves.
Knowing how to block outgoing traffic helps prevent data leaks and limits damage if a pod is compromised.
5
IntermediateCombining Ingress and Egress for Full Control
🤔
Concept: Show how to write policies that control both incoming and outgoing traffic simultaneously.
You can combine ingress and egress rules in one policy to tightly control pod communication. For example, allow only frontend pods to talk to backend pods on port 8080, and allow backend pods to send traffic only to a database pod on port 5432.
Result
Pods have strict, two-way communication rules, improving security posture.
Combining ingress and egress rules creates a strong security boundary around pods, reducing attack surfaces.
6
AdvancedHow Network Policies Work with Kubernetes Network Plugins
🤔Before reading on: do you think network policies work automatically in all Kubernetes clusters? Commit to your answer.
Concept: Explain that network policies require compatible network plugins to enforce rules.
Kubernetes itself defines the network policy API, but enforcement depends on the network plugin (like Calico, Cilium, or Weave). Some plugins do not support network policies, so rules will have no effect. Choosing the right plugin is essential for security.
Result
Learners understand that network policies are only effective if the cluster uses a supporting network plugin.
Knowing the dependency on network plugins prevents confusion when policies seem ignored in some clusters.
7
ExpertSurprising Effects of Default Deny and Policy Ordering
🤔Before reading on: do you think multiple network policies on the same pod combine or override each other? Commit to your answer.
Concept: Reveal how multiple policies combine and how default deny works in practice.
When multiple network policies select the same pod, their rules combine using a logical OR for allowed traffic. Also, if any policy selects a pod and defines ingress or egress rules, traffic not explicitly allowed is denied by default. This means adding one policy can change traffic flow drastically. Understanding this helps avoid accidental lockouts.
Result
Learners grasp how policies interact and the importance of carefully planning rules.
Understanding policy combination and default deny behavior is critical to avoid unexpected network outages in production.
Under the Hood
Network policies are implemented by the Kubernetes network plugin, which programs the underlying network layer (like Linux iptables or eBPF) to filter traffic. When a policy is applied, the plugin translates the policy rules into low-level firewall rules that allow or block packets based on pod IPs, ports, and labels. This filtering happens at the network interface level before traffic reaches the pod.
Why designed this way?
Kubernetes separates policy definition from enforcement to allow flexibility. Different environments and network plugins have different capabilities, so the API standardizes policy intent while letting plugins implement enforcement efficiently. This design supports a wide range of network technologies and scales well.
┌───────────────────────────────┐
│ Kubernetes Network Policy Flow │
├───────────────────────────────┤
│ 1. User writes NetworkPolicy  │
│ 2. Kubernetes API stores it   │
│ 3. Network plugin watches API  │
│ 4. Plugin converts rules to    │
│    firewall rules (iptables,   │
│    eBPF)                      │
│ 5. Packets filtered at node    │
│    network interface           │
│ 6. Allowed packets reach pods  │
│ 7. Blocked packets dropped     │
└───────────────────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does applying a network policy automatically block all traffic to pods it selects? Commit yes or no.
Common Belief:Applying a network policy blocks all traffic to the selected pods by default.
Tap to reveal reality
Reality:A network policy only blocks traffic if it defines ingress or egress rules; otherwise, it does not affect traffic. Also, traffic is allowed unless explicitly denied by rules.
Why it matters:Assuming policies block all traffic can lead to misconfigured rules and unexpected service outages.
Quick: Do network policies control traffic between nodes or only between pods? Commit your answer.
Common Belief:Network policies control all network traffic in the cluster, including node-to-node communication.
Tap to reveal reality
Reality:Network policies only control traffic to and from pods, not node-level traffic or external network traffic unless explicitly allowed.
Why it matters:Misunderstanding this can cause false confidence in cluster security and overlook node-level vulnerabilities.
Quick: If a pod has multiple network policies, do they override each other or combine? Commit your answer.
Common Belief:Multiple network policies on the same pod override each other; only one applies at a time.
Tap to reveal reality
Reality:Network policies combine their rules using a logical OR, meaning traffic allowed by any policy is permitted.
Why it matters:Not knowing this can cause unexpected open access or blocked traffic when multiple policies exist.
Quick: Do network policies work in any Kubernetes cluster by default? Commit yes or no.
Common Belief:Network policies work automatically in all Kubernetes clusters without extra setup.
Tap to reveal reality
Reality:Network policies require a network plugin that supports them; without such a plugin, policies have no effect.
Why it matters:Assuming policies work without support leads to a false sense of security.
Expert Zone
1
Network policies operate at Layer 3 and 4 (IP and TCP/UDP), so they cannot filter HTTP or application-layer data; for that, service meshes or proxies are needed.
2
Label selectors in network policies are powerful but can cause unintended effects if labels change dynamically or are inconsistent across namespaces.
3
Some network plugins support advanced features like egress gateway or policy logging, which can help in auditing and troubleshooting but require extra configuration.
When NOT to use
Network policies are not suitable for application-layer security or complex traffic routing; in those cases, use service meshes like Istio or Linkerd. Also, if your cluster network plugin does not support network policies, consider switching plugins or using external firewalls.
Production Patterns
In production, teams often start with a default deny all ingress and egress policy, then incrementally allow traffic needed for services. They use namespaces and labels to group pods and apply policies at scale. Monitoring and logging network policy effects is common to detect misconfigurations early.
Connections
Firewall Rules
Network policies are a Kubernetes-specific form of firewall rules controlling traffic at the pod level.
Understanding traditional firewall concepts helps grasp how network policies filter traffic based on IPs and ports.
Zero Trust Security Model
Network policies implement zero trust principles by default denying all traffic and explicitly allowing only trusted communication.
Knowing zero trust helps appreciate why network policies restrict pod communication tightly to reduce attack surfaces.
Traffic Control in Urban Planning
Both network policies and urban traffic control regulate flow to prevent congestion and accidents.
Seeing network policies as traffic controllers in a city helps understand their role in managing safe and efficient communication.
Common Pitfalls
#1Assuming network policies block traffic without defining rules.
Wrong approach:apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: empty-policy spec: podSelector: matchLabels: app: myapp
Correct approach:apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: deny-all-ingress spec: podSelector: matchLabels: app: myapp policyTypes: - Ingress ingress: []
Root cause:Not specifying ingress or egress rules means the policy does not restrict traffic, leading to false assumptions about security.
#2Writing policies without considering network plugin support.
Wrong approach:Applying network policies on a cluster using a plugin that does not support them, expecting enforcement.
Correct approach:Verify network plugin supports network policies (e.g., Calico) before applying policies.
Root cause:Lack of knowledge about cluster network plugin capabilities causes policies to be ineffective.
#3Using broad pod selectors that unintentionally include more pods.
Wrong approach:podSelector: matchLabels: app: frontend
Correct approach:podSelector: matchLabels: app: frontend environment: production
Root cause:Overly broad selectors cause policies to apply to unintended pods, leading to unexpected traffic blocking or allowing.
Key Takeaways
Kubernetes network policies control pod communication by defining rules that allow or block traffic based on labels, ports, and namespaces.
By default, pods can communicate freely; applying network policies introduces a deny-by-default behavior for selected pods, improving security.
Network policies require a compatible network plugin to enforce rules; without it, policies have no effect.
Multiple network policies on the same pod combine their rules, so understanding their interaction is key to avoiding misconfigurations.
Network policies operate at the network layer and are part of a layered security approach, complementing other tools like service meshes and RBAC.