Kubernetes 出口规则阻止所有传出流量

Kubernetes egress rule blocks all outgoing traffic

问题

我已经定义了一个从 pod test-1 到特定 pod test-2 的 kubernetes egress 规则,但是这个规则块也阻止了从 test-1test-2:

  1. 我创建了两个 pods:test-1test-2
  2. 我创建了一个网络策略,只允许从 test-1test-2
  3. egress 流量
  4. 我试图通过 curl test-2test-1 呼叫 test-2。但是这个调用被阻止了!
  5. 我检查了选择器

两个选择器 return 预期的广告连播:

kubectl describe networkpolicies test-1-policy
kubectl get pod --selector app.kubernetes.io/name=test-1
kubectl get pod --selector app.kubernetes.io/name=test-2

当我删除 networkpolicy 时,curl test-2 连接有效。

我的问题:我错过了什么?

重现问题的方法如下

  1. 将 yaml 粘贴到文件 deployment.yaml(见下文)
  2. 部署演示kubectl apply -f deployment.yaml
  3. 执行到 pod:kubectl exec --stdin --tty $(kubectl get pod -l app.kubernetes.io/name=test-1 -o jsonpath="{.items[0].metadata.name}") -- /bin/bash
  4. pod 中的调用请求:curl test-2 => 请求被阻止
  5. 删除网络策略:kubectl delete networkpolicy test-1-policy
  6. 在 pod 中执行并调用请求 => 请求已执行

这是完整的 yaml:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: test-1
  labels:
    app.kubernetes.io/name: test-1
spec:
  replicas: 1
  selector:
    matchLabels:
      app.kubernetes.io/name: test-1
  template:
    metadata:
      labels:
        app.kubernetes.io/name: test-1
    spec:
      containers:
        - name: nginx
          image: nginx
          ports:
            - name: http
              containerPort: 80
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: test-2
  labels:
    app.kubernetes.io/name: test-2
spec:
  replicas: 1
  selector:
    matchLabels:
      app.kubernetes.io/name: test-2
  template:
    metadata:
      labels:
        app.kubernetes.io/name: test-2
    spec:
      containers:
        - name: nginx
          image: nginx
          ports:
            - name: http
              containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
  name: test-1
  labels:
    app.kubernetes.io/name: test-1
spec:
  type: ClusterIP
  ports:
    - port: 80
      targetPort: http
      name: http
  selector:
    app.kubernetes.io/name: test-1
---
apiVersion: v1
kind: Service
metadata:
  name: test-2
  labels:
    app.kubernetes.io/name: test-2
spec:
  type: ClusterIP
  ports:
    - port: 80
      targetPort: http
      name: http
  selector:
    app.kubernetes.io/name: test-2
---
kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
  name: test-1-policy
spec:
  podSelector:
    matchLabels:
      app.kubernetes.io/name: test-1
  policyTypes:
    - Ingress
    - Egress
  ingress: []
  egress:
    - to:
        - podSelector:
            matchLabels:
              app.kubernetes.io/name: test-2
      ports:
        - port: 80
          protocol: TCP

缺少 dns egress 规则:

当您为 port 53 添加 egress 规则时,一切都按预期进行:

  egress:
    - ports:
      - port: 53
        protocol: UDP
      - port: 53
        protocol: TCP

https://github.com/ahmetb/kubernetes-network-policy-recipes/blob/master/11-deny-egress-traffic-from-an-application.md