Egress Rules Basics
What you'll learn: How to define egress rules in Kubernetes NetworkPolicies to control which external destinations your pods can send traffic to.
What Are Egress Rules?
While ingress rules control incoming traffic to pods, egress rules control outgoing traffic from selected pods. Think of egress rules as a whitelist that specifies which external services, IPs, or other pods your application is allowed to communicate with. Without explicit egress rules, pods might be able to send traffic anywhere—egress rules lock this down.
Why Control Egress?
In a security-conscious environment, you want to prevent compromised or misbehaving pods from:
- Exfiltrating data to unauthorized external servers
- Accessing internal services they shouldn't communicate with
- Making unnecessary API calls that could incur costs or expose sensitive data
Egress rules enforce the principle of least privilege: pods can only reach destinations they explicitly need.
Basic Egress Rule Structure
In a NetworkPolicy, you define egress alongside your pod selection criteria:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-specific-egress
spec:
podSelector:
matchLabels:
app: frontend
policyTypes:
- Egress
egress:
- to:
- podSelector:
matchLabels:
app: backend
ports:
- protocol: TCP
port: 8080
This policy selects pods labeled app: frontend and allows them to send traffic only to pods labeled app: backend on TCP port 8080. Any other outbound connections would be blocked.
Key Takeaway: Egress rules define which destinations selected pods can send traffic to, enabling fine-grained control over outbound connections and preventing unauthorized data leaks or communication.