如何将 Pod 出口流量限制为仅限外部

How to restrict pod egress traffic only to external

我需要限制流向外部目的地的 pod 出口流量。 Pod 应该能够访问互联网上的任何目的地,并且应该拒绝所有集群内部目的地。

这是我尝试过的方法,但未通过验证:

apiVersion: networking.istio.io/v1beta1
kind: Sidecar
metadata:
  name: test
spec:
  workloadSelector:
    labels:
      k8s-app: mypod

  outboundTrafficPolicy:
    mode: REGISTRY_ONLY    

  egress: 
    - hosts:
        - 'default/*'
apiVersion: networking.istio.io/v1alpha3
kind: ServiceEntry
metadata:
  name: all-external

spec:
  location: MESH_EXTERNAL
  resolution: DNS
  hosts:
    - '*'
  ports:
    - name: http
      protocol: HTTP
      number: 80
    - name: https
      protocol: TLS
      number: 443

Istio 1.11.4

我用 NetworkPolicy 做到了。允许流量到 kubernetes 和 istio 相关服务(可能会更严格,而不仅仅是基于名称space):

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: myapp-eg-system

spec:
  podSelector:
    matchLabels:
      app: myapp

  policyTypes:
    - Egress

  egress:
    - to:
      - namespaceSelector:
          matchLabels:
            kubernetes.io/metadata.name: kube-system
      - namespaceSelector:
          matchLabels:
            kubernetes.io/metadata.name: istio-system

允许除集群网络 IP 之外的任何内容 space:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: myapp-eg-app

spec:
  podSelector:
    matchLabels:
      app: myapp

  policyTypes:
    - Egress

  egress:
    - to:
      # Restrict to external traffic
      - ipBlock:
          cidr: '0.0.0.0/0'
          except:
            - '172.0.0.0/8'

      - podSelector:
          matchLabels:
            app: myapp

      ports:
        - protocol: TCP