Video in progress

Strong Middle 🧩 Microservices

In Kubernetes, how do you restrict which service can connect to which? What does NetworkPolicy give you and what doesn't it?

By default, any pod in the cluster can connect to any pod. NetworkPolicy gives an allow list at the L3/L4 level by namespace and labels: for example, only payment-service connects to payment-db. It does not cryptographically verify who is calling and does not know the HTTP path. That is the job of mTLS and authorization.

📖 Answer

Why you need it: a vulnerability in one service (SSRF or an old library) gives an attacker access to a pod. If the network is open, from there they go straight to other services' DBs, admin endpoints and Redis.

The usual approach is "default deny" and then explicit allows:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny-ingress
  namespace: payments
spec:
  podSelector: {}
  policyTypes: [Ingress]
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: payment-from-orders
  namespace: payments
spec:
  podSelector:
    matchLabels: { app: payment-service }
  ingress:
    - from:
        - namespaceSelector:
            matchLabels: { kubernetes.io/metadata.name: orders }
          podSelector:
            matchLabels: { app: order-service }
      ports:
        - port: 8080

A namespaceSelector and a podSelector in a single from element are an AND condition: the order-service pods in the orders namespace.

Pitfalls:

  • The CNI plugin enforces NetworkPolicy (Calico, Cilium). If the plugin doesn't support it, the policies are silently ignored, so after creating them verify that they really block.
  • If you restrict egress as well, don't forget to allow DNS (kube-dns, port 53 UDP/TCP), otherwise everything breaks "for no reason".
  • Prometheus and the ingress controller are traffic too, and they need allow rules as well.

NetworkPolicy works at the IP and port level. It doesn't know a rule like "order-service can call GET /payments/{id} but not POST /refunds". That is done by the service's own authorization or by the service mesh's L7 policies (for example, Istio AuthorizationPolicy with an mTLS identity). In practice you use both together: NetworkPolicy is the outer wall, mTLS and authorization are the lock on every door.