簡體   English   中英

Kube.netes NetworkPolicy 允許外部流量進出 inte.net 但不允許 Pod 到 Pod 流量

[英]Kubernetes NetworkPolicy allow external traffic from and to internet but no Pod-to-Pod traffic

我如何定義 my.networkpolicy 以便可以從集群外部訪問同一命名空間中的兩個 pod(test-server 和 test-server2)但不能相互訪問?

$ kubectl get pods
NAME                               READY   STATUS    RESTARTS   AGE
test-server-7555d49f48-sfzv9        1/1     Running   0          63m
test-server2-55c9cc78d4-knn59       1/1     Running   0          100m
# test: deny all ingress traffic
kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
  name: deny-all-ingress
spec:
  podSelector: {}
  policyTypes:
  - Ingress
# test: allow ingress traffic for test-server service
kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
  name: allow-test-server-ingress
spec:
  podSelector:
    matchLabels:
      app: test-server
  policyTypes:
  - Ingress
  ingress:
  - {}

---
# test: allow ingress traffic for test-server2 service
kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
  name: allow-test-server2-ingress
spec:
  podSelector:
    matchLabels:
      app: test-server2
  policyTypes:
  - Ingress
  ingress:
  - {}

使用這種方法,兩種服務都可以從外部訪問,但您也可以從一種服務跳轉到另一種服務。

如何定義我的network policy ,以便同一命名空間中的兩個 pod(test-server 和 test-server2)可以從集群外部訪問但不能相互訪問?

根據您的設置,您的NetworkPolicy應該與此類似

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: codewizard-block-policy
  namespace: codewizard
spec:
  # You can also add podSelection to 
  # be more specific.... (up to you)
  podSelector: {}

  policyTypes:
  - Ingress
  - Egress

  ingress:
  - from:
    # Block all traffic from the same subnet (10.10.10.10)
    # Or change the rule to only block a given IP and not a subnet
    - ipBlock:
        cidr: 10.10.10.10/32
        except:
        - 172.17.0.0/16 
    # Add allow ip from your LoadBalancer IP
  
  # Same thing for out going traffic
  egress:
  - to:
    - ipBlock:
        cidr: 0.0.0.0/0
        except:
        - 172.17.0.0/16

  • 另一種解決方案可能是使用帶有以下注釋的Ingressingress.kubernetes.io/whitelist-source-range: "xxxx/xx"
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: whitelist
  annotations:
    ingress.kubernetes.io/whitelist-source-range: "1.1.1.1/24"
spec:
  rules:
  - host: whitelist.test.net
  http:
    paths:
    - path: /
    backend:
      serviceName: webserver
     servicePort: 80

假設流量通過入口(控制器)進入,您還可以將ingress流量限制到入口 pod,如下所示:

  ingress:
  - from:
    # only allow the Ingress controller to reach the pod, this forbids pod-to-pod traffic (only for those that match the policy's podSelector)
    - podSelector:
        matchLabels:
          app.kubernetes.io/name=ingress-nginx #(or any other label specific to your ingress controller)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM