Course contentsShow
← Docker, Kubernetes & CI/CD
Lesson 81 of 8021. Container FundamentalsFree lesson

Securing Container Traffic with Network Policies

Define granular ingress and egress rules to control and restrict traffic flow between specific container workloads for enhanced security posture.

In this lesson, you will learn how to implement granular ingress and egress rules to restrict how your containers talk to one another, ensuring that only authorized traffic flows between your services.

Understanding Traffic Control

By default, containers within a network can often communicate freely. This is a security risk; if one container is compromised, an attacker could move laterally to other sensitive services. To prevent this, we use Network Policies. Think of these as a firewall specifically for your container workloads.

  • Ingress rules control the traffic coming into a container.
  • Egress rules control the traffic going out of a container to other destinations.

Instead of allowing all connections, we define a "whitelist." For example, if you have a web application container and a database container, you should configure a policy that allows the web container to send traffic to the database, but denies the database from initiating connections to anything else.

Implementing Granular Rules

When you define these rules, you aren't just opening ports; you are specifying the "Who" and the "Where." In a declarative environment, you create a policy that targets a specific label. Here is a conceptual example of a rule that restricts a backend service to only accept traffic from the frontend:

# Conceptual Network Policy Rule
ingress:
  - from:
    - podSelector:
        matchLabels:
          app: frontend
  ports:
    - protocol: TCP
      port: 5432

In this snippet, the database is essentially saying, "I will only accept TCP traffic on port 5432, and only if it originates from a container labeled as 'frontend'." Any other container attempting to talk to the database is silently dropped.

By applying these policies, you move away from an "open by default" network and toward a Zero Trust model. This limits the blast radius of a potential breach, as an attacker would be unable to scan or probe the rest of your network, even if they gain control of a single container.

Key Takeaway: Network policies allow you to enforce the principle of least privilege at the network layer by explicitly defining exactly which containers are permitted to communicate, effectively blocking all unauthorized lateral movement.