設定多網路網路政策


本頁面說明如何設定專門套用至指定 Pod 網路的多重網路政策,以提升叢集內的網路安全和流量控管。這類多重網路網路政策會使用 Pod 層級的防火牆規則控管流量,並控管 Pod 和服務之間的流量。

如要瞭解多網路網路政策的運作方式,請參閱網路政策如何搭配 Pod 網路運作

需求條件

如要使用多重網路網路政策,請注意下列規定:

  • Google Cloud CLI 459 以上版本。
  • 您必須有執行下列其中一個版本的 GKE 叢集:
    • 1.28.5-gke.1293000 以上版本
    • 1.29.0-gke.1484000 以上版本
  • 叢集必須使用 GKE Dataplane V2

限制

不支援 FQDN 網路政策和 CiliumClusterWide 網路政策: 如果您在連線至多個網路的 Pod 上使用 FQDN 網路政策和 CiliumClusterWide 網路政策,這些政策會影響 Pod 的所有連線,包括未套用政策的連線。

設定多重網路網路政策

如要使用多重網路政策,請按照下列步驟操作:

  1. 建立啟用多重網路的 GKE 叢集。
  2. 建立節點集區Pod 網路
  3. 參照 Pod 網路
  4. 建立要強制執行的網路政策,並參照工作負載使用的相同 Pod 網路。

事前準備

開始之前,請確認您已完成下列工作:

  • 啟用 Google Kubernetes Engine API。
  • 啟用 Google Kubernetes Engine API
  • 如要使用 Google Cloud CLI 執行這項工作,請安裝初始化 gcloud CLI。如果您先前已安裝 gcloud CLI,請執行 gcloud components update,取得最新版本。

建立網路政策

  1. 如要建立網路政策,在與工作負載相同的 Pod 網路上強制執行規則,請在網路政策定義中參照特定 Pod 網路。

  2. 如要根據標籤或其他選取器定義所選的連入流量規則和目標 Pod,請建立標準網路政策。

    將下列範例資訊清單儲存為 sample-ingress-network-policy1.yaml

    apiVersion: networking.k8s.io/v1
    kind: NetworkPolicy
    metadata:
      name: sample-network-policy
      namespace: default
      annotations:
        networking.gke.io/network: blue-pod-network  # GKE-specific annotation for network selection
    spec:
      podSelector:
        matchLabels:
          app: test-app-2  # Selects pods with the label "app: test-app-2"
      policyTypes:
      - Ingress  # Specifies the policy applies only to incoming traffic
      ingress:
      - from:  # Allow incoming traffic only from...
        - podSelector:
            matchLabels:
              app: test-app-1  # ...pods with the label "app: test-app-1"
    
  3. 套用 sample-ingress-network-policy1.yaml 資訊清單:

    kubectl apply -f sample-ingress-network-policy1.yaml
    
  4. 如要根據標籤或其他選取器定義所選輸出流量規則和目標 Pod,請建立標準網路政策。

    將下列範例資訊清單儲存為 sample-egress-network-policy2.yaml

    apiVersion: networking.k8s.io/v1
    kind: NetworkPolicy
    metadata:
      name: sample-network-policy-2
      namespace: default
      annotations:
        networking.gke.io/network: blue-pod-network  # GKE-specific annotation (optional)
    spec:
      podSelector:
        matchLabels:
          app: test-app-2
      policyTypes:
        - Egress  # Only applies to outgoing traffic
      egress:
        - to:
            - podSelector:
                matchLabels:
                  app: test-app-3
    
  5. 套用 sample-egress-network-policy2.yaml 資訊清單:

    kubectl apply -f sample-egress-network-policy2.yaml
    

排解多重網路聯播網政策問題

如果網路政策發生問題 (無論是否套用至特定 Pod 網路),都可以執行下列指令來診斷及排解問題:

  1. kubectl get networkpolicy:列出所有網路政策物件和相關資訊。
  2. iptables-save:擷取並列出特定節點的所有 IP 位址表鏈結。您必須以根身分在節點上執行這個指令。
  3. cilium bpf policy get <endpoint-id>:從每個端點的政策對應中擷取並列出允許的 IP 位址。
  4. cilium policy selectors:列印身分和已選取這些身分的相關聯政策。
  5. cilium identity list:顯示從身分識別到 IP 位址的對應。

後續步驟