1

I have a pod called mysql-1 with ports 3306 and 3307 open.
I want to create a network policy that allow ingress connection from backend-1 to 3306 and backend-2 to 3307.
Right now all I could come up with is this policy:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: mysql-ingress-policy-1
  namespace: v2ci
spec:
  podSelector:
    matchLabels:
      app: mysql-1
      release: v2
  types:
  - Ingress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          app: backend-1
          release: v2
    - podSelector:
        matchLabels:
          app: backend-1
          release: v2
    ports:
    - protocol: TCP
      port: 3306
    - protocol: TCP
      port: 3307

The problem is that with this policy each backend pod has access to both ports.
Is it possible to combine ports with podSelector somehow or should I just create one network policy for each backend pod?

Sam
  • 209
  • 1
  • 3
  • 9
  • As far as I know, there is no obvious way to achieve such behavior. Thus, creating two network policies look like viable option. – getslaf Dec 17 '18 at 15:52
  • I came to the same conclusion too. I also looked through the k8s code to see if there's a way to combine ports and podSelectors, I didn't find any. I guess this is by design. as you said, It should be two different network policies. – Sam Dec 17 '18 at 17:22
  • I can't see the label `backend-2` in this yaml file. But apart from that, you can provide two different `- from` sections... – deHaar Sep 23 '21 at 09:54

1 Answers1

0

There is no backend-2 mentioned in your yaml file, but changing only that would not lead to the desired result.

You have to provide two different - from sections, one per backend:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: mysql-ingress-policy-1
  namespace: v2ci
spec:
  podSelector:
    matchLabels:
      app: mysql-1
      release: v2
  types:
  - Ingress
  ingress:
  # route backend-1 to port 3306
  - from:
    - podSelector:
        matchLabels:
          app: backend-1
          release: v2
    ports:
    - protocol: TCP
      port: 3306
  # route backend-2 to port 3307
  - from:
    - podSelector:
        matchLabels:
          app: backend-2  # really apply a different pod than in the other "from"
          release: v2
    ports:
    - protocol: TCP
      port: 3307
deHaar
  • 131
  • 8