CKA network policy question

Q. my-app-deployment and cache-deployment deployed, and my-app-deployment deployment exposed through a service named my-app-service . Create a NetworkPolicy named my-app-network-policy to restrict incoming and outgoing traffic to my-app-deployment pods with the following specifications:

  • Allow incoming traffic only from pods.
  • Allow incoming traffic from a specific pod with the label app=trusted
  • Allow outgoing traffic to pods.
  • Deny all other incoming and outgoing traffic.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: my-app-deployment 
spec:
  podSelector:
    matchLabels:
      app: my-app
  policyTypes:
  - Ingress
  - Egress
  ingress:
  - from:
    - podSelector: {}
    - podSelector:
        matchLabels:
          app: trusted
    ports:
    - protocol: TCP
      port: 80
  egress:
  - to:
    - podSelector: {}

Can someone pls verify if my yaml is correct or not…it would be a great help

Let me annotate the rules you have defined

  - from:
    - podSelector: {}   # Allow ANY pod in the same namespace....
    - podSelector:      # ...which makes this rule irrelevant
        matchLabels:
          app: trusted
    ports:
    - protocol: TCP
      port: 80          # The above rules are for port 80
  egress:
  - to:
    - podSelector: {}   # To any pod in the same namespace.

“Allow incoming traffic only from pods.” is a red herring. Policy rules only apply to pods. You can’t write them for e.g. services.

Therefore your error is likely this

- from:
  - podSelector: {}  # <------

Hi @Alistair_KodeKloud . thanks for your response…just wanted to ask in question it is written that:

  • Allow incoming traffic only from pods.
  • Allow incoming traffic from a specific pod with the label app=trusted

so
`- from:

  • podSelector: {} `

we have to do it in this way only…right…we have to satisfy both the condition…can you pls suggest

- from:
  - podSelector: {}

allows ALL pods, which means

  - podSelector: 
      matchLabels:
        app: trusted

does nothing, because the first rule allows everything.

oh ok got your point…
“Allow incoming traffic only from pods.”–this is a distractor…
Thanks for clearing this out…