Networking example yaml

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: complex-logic-policy
  namespace: prod
spec:
  # --- THE TARGET ---
  podSelector:
    matchLabels:
      app: backend          # This policy ONLY applies to pods with this label
  policyTypes:
  - Ingress
  - Egress

  # --- INCOMING TRAFFIC (INGRESS) ---
  ingress:
    # RULE 1: The "AND" Logic (One dash, multiple criteria)
    # MUST be from a pod with label 'app: frontend' 
    # AND that pod must be in a namespace with label 'env: prod'
    - from:
      - podSelector:
          matchLabels:
            app: frontend
        namespaceSelector:
          matchLabels:
            env: prod
      ports:
      - protocol: TCP
        port: 80

    # RULE 2: The "OR" Logic (Multiple dashes)
    # ALLOW if traffic is from 'app: admin' 
    # OR if traffic is from ANY pod in the 'debug' namespace
    - from:
      - podSelector:
          matchLabels:
            app: admin      # Dash 1
      - namespaceSelector:
          matchLabels:
            name: debug     # Dash 2 (Separate rule)

  # --- OUTGOING TRAFFIC (EGRESS) ---
  egress:
    # RULE 3: External + Internal Logic
    # Allow talking to the internal DNS server (Port 53)
    - to:
      - podSelector:
          matchLabels:
            k8s-app: kube-dns
        namespaceSelector:
          matchLabels:
            kubernetes.io/metadata.name: kube-system
      ports:
      - protocol: UDP
        port: 53

    # RULE 4: IP Range (Egress to external world)
    # Allow talking to a specific subnet, but DENY one specific IP in that range
    - to:
      - ipBlock:
          cidr: 10.0.0.0/24
          except:
          - 10.0.0.50       # This is the "Deny" inside an "Allow"