Basic Network Policy Concepts and Structure
Basic Network Policy Concepts and Structure
Network Policies consist of several key components that define their behavior. The pod selector determines which pods the policy affects, using standard Kubernetes label matching. Policy types specify whether the policy controls ingress traffic, egress traffic, or both. Ingress and egress rules define allowed traffic patterns using various selectors for precise control.
Label-based selection provides the foundation for Network Policy targeting. Policies select pods using the same label selectors used throughout Kubernetes. This consistency simplifies policy management and enables dynamic policy application as pods are created or destroyed. Careful label design becomes essential for effective network segmentation, requiring teams to plan labeling strategies that support security requirements.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: web-netpol
namespace: production
spec:
# Select pods this policy applies to
podSelector:
matchLabels:
app: web
tier: frontend
# Define policy types
policyTypes:
- Ingress
- Egress
# Ingress rules
ingress:
- from:
# Allow traffic from pods with specific labels
- podSelector:
matchLabels:
app: gateway
# Allow traffic from specific namespaces
- namespaceSelector:
matchLabels:
name: ingress-controllers
# Allow specific ports
ports:
- protocol: TCP
port: 8080
- protocol: TCP
port: 8443
# Egress rules
egress:
# Allow DNS resolution
- to:
- namespaceSelector:
matchLabels:
name: kube-system
- podSelector:
matchLabels:
k8s-app: kube-dns
ports:
- protocol: UDP
port: 53
# Allow traffic to backend services
- to:
- podSelector:
matchLabels:
app: api
tier: backend
ports:
- protocol: TCP
port: 9000
# Allow external HTTPS traffic
- to:
- ipBlock:
cidr: 0.0.0.0/0
except:
- 169.254.169.254/32 # Block metadata service
ports:
- protocol: TCP
port: 443
Empty selectors in Network Policies have special meanings that often confuse newcomers. An empty pod selector ({}
) matches all pods in the namespace. An empty namespace selector matches all namespaces. Omitting selectors entirely creates different behaviors. Understanding these nuances prevents common mistakes that could expose or isolate workloads unintentionally.