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

Securing Ingress Traffic with Port-Based Filtering

Restrict inbound traffic to specific application ports to minimize the attack surface of your services exposed to the internal cluster network.

In this lesson, you will learn how to harden your cluster by explicitly limiting which ports your applications accept connections on, effectively shrinking your attack surface.

The Problem with Flat Networks

By default, Kubernetes clusters operate on a flat network model where any pod can communicate with any other pod on any port. If a service in your cluster is compromised, an attacker could potentially scan and probe other internal services on arbitrary ports. Relying on "security by obscurity"—hoping an attacker doesn't know your app listens on port 8080—is not a viable security strategy.

Implementing Port-Based Filtering

To minimize this risk, we use Kubernetes NetworkPolicies to enforce a strict whitelist. Instead of just controlling which pods can talk to each other (via label selectors), we use the ports field to define exactly which specific network ports are allowed to receive inbound traffic.

If your application only needs to receive HTTP traffic on port 8080, your policy should explicitly drop traffic directed at any other port, such as administrative debug ports or management interfaces.

Consider this NetworkPolicy snippet:

kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
  name: allow-web-only
spec:
  podSelector:
    matchLabels:
      app: frontend
  ingress:
  - ports:
    - protocol: TCP
      port: 8080
    from:
    - podSelector:
        matchLabels:
          role: load-balancer

Why This Matters

By defining the ports block, you are implementing the Principle of Least Privilege at the transport layer. Even if a pod is misconfigured to listen on an extra port (like a management port 9090), this policy ensures that no other pod in the cluster can reach it, effectively isolating potential vulnerabilities within that specific port. Combining this with a "Default Deny All" policy ensures that if a port isn't explicitly opened in a NetworkPolicy, traffic to it is silently discarded, preventing lateral movement within your cluster.

Key Takeaway: Restricting traffic to only the necessary ports via NetworkPolicies minimizes your attack surface and prevents unauthorized internal access to non-exposed service endpoints.