4

Is it possible to allow egress traffic only to the specific service? This is my naive try to do that:

kind: NetworkPolicy
metadata:
  name: default-deny-all-egress
  namespace: default
spec:
  podSelector: {}
  egress:
  - ports:
    - protocol: TCP
      port: 53
    - protocol: UDP
      port: 53
    to:
      - podSelector:
          matchLabels:
            k8s-app: kube-dns
    
  policyTypes:
    - Egress
Jonas
  • 4,683
  • 4
  • 45
  • 81
  • "service" is not really an entity, but (with some CNI) iptable rules, so this is more virtual, that why NP always target pods – Thomas Decaux Jul 23 '21 at 13:20

1 Answers1

2

No, as far as I know you can do that only using podSelector. However, if you have an access to cluster, I think you can still manually add additional labels for needed pods and use podSelector

Create egress policies provides you good template of NetworkPolicy structure. The following policy allows pod outbound traffic to other pods in the same namespace that match the pod selector.

kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
  name: allow-egress-same-namespace
  namespace: default
spec:
  podSelector:
    matchLabels:
      color: blue
  egress:
  - to:
    - podSelector:
        matchLabels:
          color: red
    ports:
    - port: 80

I know that you can use namespaceSelector for ingress like below. Not sure you can use it with egress- havent tried. But to access to pods from other namespace you should somehow point it in the configuration

  namespaceSelector:
    matchLabels:
      shape: square
Vit
  • 7,740
  • 15
  • 40