2

Create an NetworkPolicy named cka-netpol in the namespace netpol. 1] Allow the pods to communicate if they are running on port 8080 within the namespace. 2] Ensure the NetworkPolicy doesn’t allow other pods that are running other than port 8080. 3] The communication from and to the pods running on port 8080. No pods running on port 8080 from other namespaces to allowed.

I want yaml file with some description theoretically.

  • is [this](https://github.com/alifiroozi80/CKA/tree/main/CKA#secure-cluster---network-policies) help you? – Ali Nov 01 '22 at 05:04

2 Answers2

2

Allow the pods to communicate if they are running on port 8080 within the namespace.

We will only open and accept requests on port 8080 to satisfy the above request.

The communication from and to the pods running on port 8080. No pods running on port 8080 from other namespaces to allowed.

Using namespace selector to filter out the traffic from specific namespace.

Ensure the NetworkPolicy doesn’t allow other pods that are running other than port 8080.

We have applied the network policy with port as input on the namespace level

check the namespace label

kubectl get namespace netpol --show-labels

Example YAML

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: cka-netpol
  namespace: netpol
spec:
  podSelector: {}
  policyTypes:
  - Ingress
  ingress:
  - from:
    - namespaceSelector:
        matchLabels:
          namespace: netpol #Use label accordingly
    ports:
      - protocol: TCP
        port: 8080

You check more example and use this link for ref : https://github.com/ahmetb/kubernetes-network-policy-recipes/blob/master/09-allow-traffic-only-to-a-port.md

Harsh Manvar
  • 27,020
  • 6
  • 48
  • 102
  • The only doubt I have on the 3rd point saying "The communication from and to the pods running on port 8080.". Is this point saying that we have to only allow traffic from pods running on port 8080 to pods running on port 8080?? – PRANIT BHOIR Nov 01 '22 at 07:33
0
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: cka-netpol
  namespace: netpol
spec:
  podSelector:
    matchLabels:
      role: db          #label of pod you want to create np for
  policyTypes:
    - Ingress
    - Egress
  ingress:
    - from:
        - namespaceSelector:
            matchLabels:
              project: netpol  #according to your labels of namespace
      ports:
        - protocol: TCP
          port: 8080
  egress:            #required for traffic going out
     - ports:
        - protocol: TCP
          port: 8080