Cilium Network Policies (CNPs) and CiliumClusterwideNetworkPolicies (CCNP) secure Kubernetes pod-to-pod communications by leveraging eBPF for high-performance, identity-based L3/L4 and L7 enforcement, enabling granular ingress and egress traffic rules.
Here's how to implement them:
1. Install Cilium: Deploy Cilium as your Container Network Interface (CNI) plugin. It replaces kube-proxy and utilizes eBPF for efficient packet filtering and policy enforcement directly in the Linux kernel. Ensure enable-l7-proxy is set to true if L7 policies are required.
2. Label Pods Consistently: Policy enforcement in Cilium relies heavily on Kubernetes labels. Ensure all your application pods are consistently labeled with metadata like app, tier, environment, or owner to define policy targets and sources effectively.
3. Define CiliumNetworkPolicy (CNP): Create a CiliumNetworkPolicy resource to specify allowed ingress and egress traffic for pods matching a podSelector. You can define rules based on pod labels, namespaces, service accounts, CIDR blocks, or even L7 HTTP/Kafka/gRPC attributes.
```yaml
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
name: allow-app-to-db
namespace: default
spec:
endpointSelector:
matchLabels:
app: frontend
egress:
- toEndpoints:
- matchLabels:
app: database
toPorts:
- ports:
- port: "5432"
protocol: TCP
ingress:
- fromEndpoints:
- matchLabels:
app: backend
toPorts:
- ports:
- port: "80"
protocol: TCP
```
4. Apply the Policy: Use kubectl apply -f your-policy.yaml to deploy your CiliumNetworkPolicy to the cluster. Cilium agents will automatically enforce these rules on the relevant pods.
5. Monitor and Validate: Use cilium monitor to observe real-time traffic flows and policy decisions. cilium policy get shows all active policies, and kubectl get cnp -o yaml provides details on their status.
Gotcha: When implementing a default-deny policy (e.g., via CiliumClusterwideNetworkPolicy with no endpointSelector), any new pod without an explicit CiliumNetworkPolicy allowing its necessary traffic will be blocked, potentially causing application outages. Always plan and apply policies incrementally.