Kubernetes NetworkPolicy limit egress traffic to service

3/1/2021

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
kubernetes
kubernetes-networkpolicy
project-calico

1 Answer

3/2/2021

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
Source: StackOverflow