Using Network Policies you can whitelist all pods in a namespace:
kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
name: allow-egress-to-sample
namespace: sample
spec:
policyTypes:
- Egress
podSelector: {}
egress:
- to:
- namespaceSelector:
matchLabels:
name: sample
As you probably already know, pods with at least one Network Policy applied to them can only communicate to targets allowed by any Network Policy applied to them.
Names don't actually matter. Selectors (namespaceSelector and podSelector in this case) only care about labels. Labels are key-value pairs associated with resources. The above example assumes the namespace called sample
has a label of name=sample
.
If you want to whitelist the namespace called http://my-nginx
, first you need to add a label to your namespace (if it doesn't already have one). name
is a good key IMO, and the value can be the name of the service, http://my-nginx
in this particular case (not sure if :
and /
can be a part of a label though). Then, just using this in your Network Policies will allow you to target the namespace (either for ingress or egress)
- namespaceSelector:
matchLabels:
name: http://my-nginx
If you want to allow communication to a service called my-nginx
, the service's name doesn't really matter. You need to select the target pods using podSelector, which should be done with the same label that the service uses to know which pods belong to it. Check your service to get the label, and use the key: value
in the Network Policy. For example, for a key=value pair of role=nginx you should use
- podSelector:
matchLabels:
role: nginx