Day 26/#30daysofK8s

Parthvi Vala
2 min readFeb 27, 2021

Ingress request defines an incoming request to a server, while an egress request defines the service request going from a server.

By default, k8s has an AllowAll Authorization mechanism, which means that any pod in the cluster can communicate with any other pod in the cluster.

To not allow this, one can implement NetworkPolicy on a pod, so that it only accepts ingress request from a certain component in the cluster.

NetworkPolicy uses label selector to determine which pod it takes for consideration when receiving ingress request.

networkpolicy-def.yamlapiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: db-policy
spec:
podSelector:
matchLabels:
type: db
policyTypes:
- Ingress
ingress:
- from:
- podSelector:
matchLabels:
name: api-pod
ports:
- protocol: TCP
port: 8443

This network policy only applies to pod with label type=db and will only respond to ingress requests coming from pod(in any namespaces) matching label name=api-pod and only from port 8443. Also, it will only receive requests since policyType is ingress and *won’t be able to send egress requests.

To make this a namespaced policy, we can add a namespaceSelector selector to the spec which will be just like podSelector .

To allow ingress requests from an external server which is not a part from the cluster, we can add a block to the definition file like -

...
ingress:
- from:
- podSelector:
matchLabels:
name: api-pod
namespaceSelectory:
matchLabels:
name: dev
- ipBlock:
cird: 192.168.5.10
...

Here, the policy accepts ingress requests coming from either a pod in ‘dev’ namespace matching label name=api-pod OR from an IP address 192.168.5.10

In case of egress requests, only a few things change — 1)add Egress to policyTypes , 2) use egresssection just like ingress section and, 3) use to in the egress section instead of from in the ingresssection.

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: egresspolicy
spec:
policyTypes:
- Ingress
- Egress
ingress:
...
...
egress:
- to:
podSelector:
matchLabels:
app: smh
ports:
...

--

--