kubernetes network policy - ghdrako/doc_snipets GitHub Wiki
- https://github.com/ahmetb/kubernetes-network-policy-recipes
- https://docs.tigera.io/calico/latest/network-policy/get-started/kubernetes-policy/kubernetes-network-policy
- https://snyk.io/blog/kubernetes-network-policy-best-practices/
The Kubernetes Network Policy API supports the following features:
- Policies are namespace scoped
- Policies are applied to pods using label selectors
- Policy rules can specify the traffic that is allowed to/from pods, namespaces, or CIDRs
- Policy rules can specify protocols (TCP, UDP, SCTP), named ports or port numbers
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: sample-network-policy
namespace: default
The next portion of the YAML file contains the specifications (specs) section, where we can stipulate filters to which the network policy will apply.
The below segment features several vital parameters:
- podSelector — Specifies which Pods are subject to the prescribed traffic policies. Our example uses the matchLabels parameter to ensure that the network policy applies to all Pods labeled app: wordpress. As a secondary result, the parameter excludes all other Pods from this network policy.
- policyTypes — Contains two categories: Ingress and Egress
- Ingress — Defines all incoming Pod/namespace/Pod collection traffic
- Egress — Defines all outgoing Pod/namespace/Pod collection traffic
spec:
podSelector:
matchLabels:
app: wordpress
policyTypes:
- Egress
- Ingress
The below section allows ingress on ports 443 and 80 from:
- All Pods labeled wordpress
- All public internet traffic (cidr: 0.0.0.0/0)
- All IP addresses within the range 172.16.0.0/16, which might represent a corporate IP range (a VPN, VLAN, or subnet).
ingress:
- from:
- podSelector:
matchLabels:
app: wordpress
ports:
- port: 443
- port: 80
- from:
- ipBlock:
cidr: 172.16.0.0/16
ports:
- port: 443
- port: 80
- from:
- ipBlock:
cidr: 0.0.0.0/0
ports:
- port: 443
- port: 80
We allow all outgoing traffic communication from Pods labeled webapp on ports 1433 (SQL) and 53 (DNS).
Specifying the webapp label ensures no other Pod can communicate with the SQL Server instances, eliminating all associated security risks. Similarly, the configuration allows port 53 to connect to all Pods in the cluster.
egress:
- to:
- namespaceSelector: {}
podSelector:
matchLabels:
k8s-app: kube-dns
ports:
- port: 53
protocol: UDP
- to:
- podSelector:
matchLabels:
app: wordpress
ports:
- port: 3306
kubectl apply -f sample-network-policy.yaml
kubectl describe networkpolicy sample-network-policy