I try to create a situation which is shown in the picture.
kubectl run frontend --image=nginx --labels="app=frontend" --port=30081 --expose
kubectl run backend --image=nginx --labels="app=backend" --port=30082 --expose
kubectl run database --image=nginx --labels="app=database" --port=30082
I created network policy which should block all ingress and egress access which do not have specific label definition.
kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
name: access-nginx
spec:
podSelector:
matchLabels:
app: frontend
matchLabels:
app: backend
matchLabels:
app: database
policyTypes:
- Ingress
- Egress
ingress:
- from:
- podSelector:
matchLabels:
app: frontend
matchLabels:
app: backend
matchLabels:
app: database
egress:
- to
- podSelector:
matchLabels:
app: frontend
matchLabels:
app: backend
matchLabels:
app: database
- ports:
- port: 53
protocol: UDP
- port: 53
protocol: TCP
I tried to connect to pod frontend without label(command 1) and with correct label(command 2) as is shown below.
I expected that first command which do not use label will be blocked and second command will allow communication but after pressed the second command i see output "wget: can't connect to remote host (10.109.223.254): Connection refused". Did I define network policy incorrectly?
As mentioned in kubernetes documentation about Network Policy
Prerequisites
Network policies are implemented by the network plugin. To use network policies, you must be using a networking solution which supports NetworkPolicy. Creating a NetworkPolicy resource without a controller that implements it will have no effect.
As far as I know flannel, which is used by katacoda does not support network policy.
controlplane $ kubectl get pods --namespace kube-system
NAME READY STATUS RESTARTS AGE
coredns-66bff467f8-4tmhm 1/1 Running 0 16m
coredns-66bff467f8-v2dbj 1/1 Running 0 16m
etcd-controlplane 1/1 Running 0 16m
katacoda-cloud-provider-58f89f7d9-brnk2 1/1 Running 8 16m
kube-apiserver-controlplane 1/1 Running 0 16m
kube-controller-manager-controlplane 1/1 Running 0 16m
kube-flannel-ds-amd64-h5lrd 1/1 Running 1 16m
kube-flannel-ds-amd64-sdl4b 1/1 Running 0 16m
kube-keepalived-vip-gkhbz 1/1 Running 0 16m
kube-proxy-6gd8d 1/1 Running 0 16m
kube-proxy-zkldz 1/1 Running 0 16m
kube-scheduler-controlplane 1/1 Running 1 16m
As mentioned here
Flannel is focused on networking. For network policy, other projects such as Calico can be used.
Additionally there is nice tutorial which show which CNI support network policy.
So I would say it´s not possible to do on katacoda playground.