Kubernetes CKA sample exam question 35 with answer

Question
Create a Network Policy to allow traffic from internal application only to payroll-service and db-service.
Use the spec given below:
Policy name: internal-policy
Policy typeL Egress
Egress allow: payroll
Payroll port: 8080
Egress allow: mysql
MySQL port: 3306
Allow DNS resolution possible

Answer
Get labels for all pods and check the services:

kubectl get po --show-labels
kubectl get svc
The pods have the following labels:
internal - name: internal
mysql - db: mysql
payroll -  app: payroll
Construct the netpol:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: internal-policy
  namespace: default
spec:
  podSelector:
    matchLabels:
      name: internal
  policyTypes:s
  - Egress
  egress:
  - to:
    - podSelector:
        matchLabels:
          db: mysql
    ports:
    - protocol: TCP
      port 3306
  - to:
    - podSelector:
        matchLabels:
          app: payroll
    ports:
    - protocol: TCP
      port 8080
  - ports:
    - protocol: UDP
      port 53
    - protocol: TCP
      port 53
Apply and check:
kubectl apply -f np.yaml
kubectl describe netpol internal-policy