Course contentsShow
← Cloud and Infrastructure
Lesson 1235 of 2,98924. Kubernetes NetworkingFree lesson

NetworkPolicy Specification Structure

Learn the YAML structure of NetworkPolicy resources including podSelector, policyTypes, and rule definitions.

NetworkPolicy Specification Structure

What you'll learn: How to read and write the YAML structure that defines Kubernetes NetworkPolicies, including selecting pods and defining traffic rules.

Understanding the YAML Blueprint

A NetworkPolicy is like a firewall rule written in YAML. Just as you learned how pods and services have specific manifest structures, NetworkPolicies follow their own predictable pattern. Think of it as a form with three key sections: who the policy applies to, what type of traffic it controls, and what traffic is allowed.

The Core Components

Every NetworkPolicy manifest contains these essential fields:

podSelector — Identifies which pods this policy governs using label matching (just like you learned with ReplicaSets and Services). An empty selector {} means "all pods in this namespace."

policyTypes — An array declaring whether the policy controls Ingress (incoming traffic), Egress (outgoing traffic), or both. Without this field, Kubernetes guesses based on the rules present.

ingress — A list of rules allowing incoming connections. Each rule can specify sources (which pods or IP ranges can connect).

egress — A list of rules allowing outgoing connections. Each rule can specify destinations (where pods can send traffic).

Basic Structure Example

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: my-policy
  namespace: default
spec:
  podSelector:
    matchLabels:
      app: backend
  policyTypes:
  - Ingress
  - Egress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          role: frontend
    ports:
    - protocol: TCP
      port: 8080

This policy applies to pods labeled app: backend, allows TCP traffic on port 8080 from pods labeled role: frontend, and because Egress is declared without rules, blocks all outbound traffic.

Key Takeaway: NetworkPolicy specs use podSelector to target pods, policyTypes to declare traffic direction, and ingress/egress rule lists to define allowed connections—forming a declarative firewall configuration in YAML.