Course contentsShow
← Docker, Kubernetes & CI/CD
Lesson 518 of 8028. Security and ObservabilityFree lesson

Restricting Inter-Pod Traffic Using Label Selectors

Configure fine-grained network policies to allow specific pods to communicate based on metadata labels rather than relying on unstable IP addresses.

In this lesson, you will learn how to transition from broad network security to granular traffic control by using label selectors to define precisely which pods are allowed to communicate.

Moving Beyond IP Addresses

By default, Kubernetes follows a "flat network" model where every pod can talk to every other pod. While we previously established a "Default Deny All" policy to secure our cluster, we now need a way to selectively re-enable communication. Relying on pod IP addresses for this is impossible because IPs are ephemeral and change whenever a pod restarts. Instead, we use Label Selectors, which allow us to define traffic rules based on the persistent metadata assigned to our resources.

Configuring Granular Access

Network policies act like a firewall for your pods. When you write a policy, you define ingress or egress rules using podSelector fields. This tells Kubernetes: "Only allow traffic if the source or destination pod carries this specific label."

For example, if you want your frontend pods to talk to your database pods, you would apply a policy to the database pods that looks like this:

kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
  name: allow-frontend-to-db
spec:
  podSelector:
    matchLabels:
      app: database
  ingress:
  - from:
    - podSelector:
        matchLabels:
          app: frontend

In this configuration, even if the database pod changes its IP address due to a deployment rollout, the NetworkPolicy remains valid. Because the policy is tied to the app: frontend label, Kubernetes automatically updates the rules as pods are created or destroyed, ensuring that only the authorized frontend pods can reach the database.

By leveraging labels, you decouple your security posture from your network infrastructure. This allows your security policies to remain stable even as your cluster scales or undergoes maintenance. It is the most robust way to enforce the principle of least privilege in a dynamic, containerized environment.

Key Takeaway: Use label selectors in your NetworkPolicies to create immutable security rules that stay attached to your services, regardless of how often their underlying IP addresses change.